def getSession(self): """Return the existing session or a new session""" if self.session is not None: return self.session # Get value of cookie header that was sent cookie_str = self.headers.get('Cookie') if cookie_str: cookie_obj = SimpleCookie(cookie_str) sid_morsel = cookie_obj.get(self.SESSION_COOKIE_NAME, None) if sid_morsel is not None: sid = sid_morsel.value else: sid = None else: sid = None # If a session id was not set, create a new one if sid is None: sid = randomString(16, '0123456789abcdef') session = None else: session = self.server.sessions.get(sid) # If no session exists for this session ID, create one if session is None: session = self.server.sessions[sid] = {} session['id'] = sid self.session = session return session
def getSession(self): """Return the existing session or a new session""" if self.session is not None: return self.session # Get value of cookie header that was sent if self.get_cookie(self.SESSION_COOKIE_NAME): sid = self.get_cookie(self.SESSION_COOKIE_NAME) else: sid = None # If a session id was not set, create a new one if sid is None: sid = randomString(16, '0123456789abcdef') session = None else: session = self.session[sid] # If no session exists for this session ID, create one if session is None: session = {} session['id'] = sid self.session = session return session
def _sorry_no_identity(self): request = self.request _ = self._ request.theme.send_title(_("OpenID not served"), pagename=request.page.page_name) # Start content (important for RTL support) request.write(request.formatter.startContent("content")) request.write(request.formatter.paragraph(1)) request.write(_(''' Unfortunately you have not created your homepage yet. Therefore, we cannot serve an OpenID for you. Please create your homepage first and then reload this page or click the button below to cancel this verification.''')) request.write(request.formatter.paragraph(0)) form = html.FORM(method='POST', action=request.page.url(request)) form.append(html.INPUT(type='hidden', name='action', value='serveopenid')) nonce = randomString(32, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') form.append(html.INPUT(type='hidden', name='nonce', value=nonce)) request.session['openidserver.nonce'] = nonce form.append(html.INPUT(type='submit', name='dontapprove', value=_("Cancel"))) request.write(unicode(form)) request.write(request.formatter.endContent()) request.theme.send_footer(request.page.page_name) request.theme.send_closing_html()
def cas_authenticate(self, req, dbname, cur_url, cas_host, auto_create, ticket): """ Checks if the user attempts to authenticate is authorized to do it and, if it is, authenticate him. """ # cas_server = cas_host + ':' + cas_port cas_server = cas_host service_url = urllib.quote(cur_url, safe='') # The login function, from pycas, check if the ticket given by # CAS is a real ticket. The login of the user # connected by CAS is returned. status, idUser, cookie = login(cas_server, service_url, ticket) result = False if idUser and status == 0: cr = pooler.get_db(dbname).cursor() registry = RegistryManager.get(dbname) users = registry.get('res.users') ids = users.search(cr, SUPERUSER_ID, [('login', '=', idUser)]) assert len(ids) < 2 # We check if the user authenticated have an OpenERP account or if # the auto_create field is True if ids or auto_create == 'True': if ids: user_id = ids[0] # If the user have no account, we create one else: user_id = users.create(cr, SUPERUSER_ID, { 'name': idUser.capitalize(), 'login': idUser }) # A random key is generated in order to verify if the # login request come from here or if the user # try to authenticate by any other way cas_key = randomString(16, '0123456789abcdefghijklmnopqrstuvwxyz') users.write(cr, SUPERUSER_ID, [user_id], {'cas_key': cas_key}) cr.commit() login_and_redirect(dbname, idUser, cas_key) result = {'status': status, 'session_id': req.session_id} else: result = { 'status': status, 'fail': True, 'session_id': req.session_id } cr.close() if not result: result = {'status': status} return result
def write_user(self, lp_user): """Writes a launchpad user record into our user cache, resolving the openid if necessary. :param lp_user: The launchpad user record. :return: The SQLAlchemy entity for the user record. """ try: display_name = lp_user.display_name user_link = lp_user.web_link except errors.HTTPError: display_name = "Disabled Launchpad User" user_link = "000000000000000000000" # Resolve the openid. if user_link not in self._openid_map: try: openid_consumer = consumer.Consumer( dict(id=cryptutil.randomString(16, '0123456789abcdef')), None) openid_request = openid_consumer.begin(user_link) openid = openid_request.endpoint.getLocalID() openid = openid.replace( 'login.launchpad.net', 'login.ubuntu.com') self._openid_map[user_link] = openid except DiscoveryFailure: # If we encounter a launchpad maintenance user, # give it an invalid openid. print("WARNING: Invalid OpenID for user \'%s\'" % (display_name,)) self._openid_map[user_link] = \ 'http://example.com/invalid/~%s' % (display_name,) openid = self._openid_map[user_link] # Resolve the user record from the openid. if openid not in self._user_map: # Check for the user, create if new. user = db_api.model_query(User, self.session) \ .filter_by(openid=openid) \ .first() if not user: print("Importing user '%s'" % (user_link)) # Use a temporary email address, since LP won't give this to # us and it'll be updated on first login anyway. user = db_api.entity_create(User, { 'openid': openid, 'full_name': display_name, 'email': "*****@*****.**" % (display_name, uuid.uuid4()) }, session=self.session) self._user_map[openid] = user return self._user_map[openid]
def write_user(self, lp_user): """Writes a launchpad user record into our user cache, resolving the openid if necessary. :param lp_user: The launchpad user record. :return: The SQLAlchemy entity for the user record. """ if lp_user is None: return lp_user display_name = lp_user.display_name user_link = lp_user.web_link # Resolve the openid. if user_link not in self._openid_map: try: openid_consumer = consumer.Consumer( dict(id=cryptutil.randomString(16, '0123456789abcdef')), None) openid_request = openid_consumer.begin(user_link) openid = openid_request.endpoint.getLocalID() self._openid_map[user_link] = openid except DiscoveryFailure: # If we encounter a launchpad maintenance user, # give it an invalid openid. print "WARNING: Invalid OpenID for user \'%s\'" \ % (display_name,) self._openid_map[user_link] = \ 'http://example.com/invalid/~%s' % (display_name,) openid = self._openid_map[user_link] # Resolve the user record from the openid. if openid not in self._user_map: # Check for the user, create if new. user = db_api.model_query(User, self.session) \ .filter_by(openid=openid) \ .first() if not user: print "Importing user '%s'" % (user_link) # Use a temporary email address, since LP won't give this to # us and it'll be updated on first login anyway. user = db_api.entity_create( User, { 'openid': openid, 'full_name': display_name, 'email': "*****@*****.**" % (display_name) }, session=self.session) self._user_map[openid] = user return self._user_map[openid]
def getSession(self, expiration_ts=gaesession.DEFAULT_LIFETIME_SEC): """Return the existing session or a new session""" session = gaesession.get_current_session() if not session.has_key( 'id' ): session.start( ssl_only=OPENID_SESSION_SSL_ONLY, expiration_ts=expiration_ts ) sid = randomString(16, '0123456789abcdef') session['id'] = sid return session
def sessionId(self): if not self._sessionId: sid = None if 'HTTP_COOKIE' in self.environment: cookieObj = SimpleCookie(self.environment['HTTP_COOKIE']) morsel = cookieObj.get(self.SESSION_COOKIE_NAME, None) if morsel is not None: self._sessionId = morsel.value if self._sessionId: self.loadSession() else: self._sessionId = randomString(16, '0123456789ABCDEF') return self._sessionId
def get_session(self): oidsession = cherrypy.session.get(self.session_name, None) if not oidsession or not isinstance(oidsession, dict): oidsession = {} if "sid" not in oidsession: sid = randomString(16, "0123456789abcdef") oidsession["sid"] = sid cherrypy.session[self.session_name] = oidsession cherrypy.session[self.session_name]["status"] = UNKNOWN return cherrypy.session[self.session_name]
def cas_authenticate(self, req, dbname, cur_url, cas_host, auto_create, ticket): """ Checks if the user attempts to authenticate is authorized to do it and, if it is, authenticate him. """ # cas_server = cas_host + ':' + cas_port cas_server = cas_host service_url = urllib.quote(cur_url, safe='') # The login function, from pycas, check if the ticket given by CAS is a real ticket. The login of the user # connected by CAS is returned. status, idUser, cookie = login(cas_server, service_url, ticket) result = False if idUser and status == 0: cr = pooler.get_db(dbname).cursor() registry = RegistryManager.get(dbname) users = registry.get('res.users') ids = users.search(cr, SUPERUSER_ID, [('login', '=', idUser)]) assert len(ids) < 2 # We check if the user authenticated have an OpenERP account or if # the auto_create field is True if ids or auto_create == 'True': if ids: user_id = ids[0] # If the user have no account, we create one else: user_id = users.create( cr, SUPERUSER_ID, {'name': idUser.capitalize(), 'login': idUser}) # A random key is generated in order to verify if the login request come from here or if the user # try to authenticate by any other way cas_key = randomString( 16, '0123456789abcdefghijklmnopqrstuvwxyz') users.write(cr, SUPERUSER_ID, [user_id], {'cas_key': cas_key}) cr.commit() login_and_redirect(dbname, idUser, cas_key) result = {'status': status, 'session_id': req.session_id} else: result = { 'status': status, 'fail': True, 'session_id': req.session_id} cr.close() if not result: result = {'status': status} return result
def getAuthKey(self): key = OidStoreSetting.objects.get(setting = "auth_key") if key.count() == 0: auth_key = cryptutil.randomString(self.AUTH_KEY_LEN) s = OidStoreSetting(setting = "auth_key", value = self.blobEncode(auth_key)) s.save() else: auth_key = self.blobDecode(key.value) if len(auth_key) != self.AUTH_KEY_LEN: fmt = "Expected %d-byte string for auth key, got %r" raise ValueError(fmt % (self.AUTH_KEY_LEN, auth_key)) return auth_key
def getsession(self, environ): '''Return the existing session or a new session''' # Get value of cookie header that was sent sid = self.getsid(environ) # If a session id was not set, create a new one if sid is None: sid = randomString(16, '0123456789abcdef') session = None else: session = self.tracker.get(sid) # If no session exists for this session ID, create one if session is None: session = self.tracker[sid] = {} session['redirect'] = geturl(environ) session['id'] = sid return session
def get_session(): # Get value of cookie header that was sent sid = request.cookies.get(SESSION_COOKIE_NAME) # If a session id was not set, create a new one if sid is None: sid = randomString(16, '0123456789abcdef') session = None else: session = SESSIONS.get(sid) # If no session exists for this session ID, create one if session is None: session = SESSIONS[sid] = {} session['id'] = sid return session
def login(): if 'SESSION_ID' not in request.cookies: session_id = randomString(16, '0123456789abcdef') else: session_id = request.cookies['SESSION_ID'] oidconsumer = consumer.Consumer({'id': session_id}, None) oidrequest = oidconsumer.begin(u'http://ru.wargaming.net/id/openid/') print(oidrequest.shouldSendRedirect()) redirect_url = oidrequest.redirectURL( realm='http://127.0.0.1:5000/', return_to='http://127.0.0.1:5000/auth_cb', ) print(oidrequest.shouldSendRedirect()) response = redirect(redirect_url) response.set_cookie('SESSION_ID', session_id) return response
def getLPUser(self, lp_user): log.debug("Getting info about %s" % lp_user.name) # only call this if we have no info for a user member = launchpad.people[lp_user.name] openid_consumer = consumer.Consumer(dict(id=randomString(16, "0123456789abcdef")), None) openid_request = openid_consumer.begin("https://launchpad.net/~%s" % member.name) openid = openid_request.endpoint.getLocalID() lp_user.openids.append(openid) self.openids[openid] = lp_user try: lp_user.email = member.preferred_email_address.email except ValueError: pass for key in member.sshkeys: lp_user.ssh_keys.append("%s %s %s" % (get_type(key.keytype), key.keytext, key.comment))
def loginUser(self): cursor = self.db().cursor() cursor.execute('SELECT user FROM identities WHERE identity=%s', (self.session['oid'],)) row = cursor.fetchone() if row: self.session['userId'] = row[0] cursor.execute('SELECT secret, username, public FROM users WHERE id=%s', (row[0],)) secret, username, public = cursor.fetchone() self.session['secret'] = secret self.session['username'] = username self.session['public'] = public else: self.session['secret'] = randomString(16, '0123456789ABCDEF') self.session['username'] = None self.session['public'] = False cursor.execute('INSERT INTO users (secret) VALUES (%s)', (self.session['secret'],)) self.session['userId'] = cursor.lastrowid cursor.execute('INSERT INTO identities (user, identity) VALUES (%s, %s)', (self.session['userId'], self.session['oid'])) self.db().commit() cursor.close()
def mkNonce(when=None): """Generate a nonce with the current timestamp @param when: Unix timestamp representing the issue time of the nonce. Defaults to the current time. @type when: int @returntype: str @returns: A string that should be usable as a one-way nonce @see: time """ salt = cryptutil.randomString(6, NONCE_CHARS) if when is None: t = gmtime() else: t = gmtime(when) time_str = strftime(time_fmt, t) return time_str + salt
def add_user(self, user_name, user_data): logger.info("Adding Gerrit user %s", user_name) openid_consumer = consumer.Consumer(dict(id=randomString(16, '0123456789abcdef')), None) openid_request = openid_consumer.begin("https://launchpad.net/~%s" % user_data.name) user_openid_external_id = openid_request.endpoint.getLocalID() query= "select account_id from account_external_ids where external_id in ('{0}')".format(user_openid_external_id) stdout= self.run_query(query) row= json.loads(stdout.readline()) if row['type'] == 'row': # we have a result so this is an updated user name account_id= row['columns']['account_id'] query= "update account_external_ids set external_id='{0}' where external_id like 'username%%' and account_id = {1}".format('username:%s' % user_name, account_id) self.run_query(query) else: # we really do have a new user user_ssh_keys= ["%s %s %s" % ('ssh-%s' % key.keytype.lower(), key.keytext, key.comment) for key in user_data.sshkeys] user_email= None try: email = user_data.preferred_email_address.email except ValueError: pass query= "insert into account_id (s) values (NULL)" self.run_query(query) query= "select max(s) from account_id" stdout= self.run_query(query) row= json.loads(stdout.readline()) uid= row['columns']['max(s)'] query= "insert into accounts (account_id, full_name, preferred_email) values ({0}, '{1}', '{2}')".format(uid, user_name, user_email) self.run_query(query) keyno= 1 for key in user_ssh_keys: query= "insert into account_ssh_keys (ssh_public_key, valid, account_id, seq) values ('{0}', 'Y', {1}, {2})".format(key.strip(), uid, keyno) self.run_query(query) keyno = keyno + 1 query= "insert into account_external_ids (account_id, email_address, external_id) values ({0}, '{1}', '{2}')".format(uid, user_email, user_openid_external_id) self.run_query(query) query= "insert into account_external_ids (account_id, external_id) values ({0}, '{1}')".format(uid, "username:%s" % user_name) self.run_query(query) if user_email is not None: query= "insert into account_external_ids (account_id, email_address, external_id) values ({0}. '{1}', '{2}')".format(uid, user_email, "mailto:%s" % user_email) return None
def createAuthKey(self): """Generate a new random auth key and safely store it in the location specified by self.auth_key_name. () -> str""" # Do the import here because this should only get called at # most once from each process. Once the auth key file is # created, this should not get called at all. auth_key = cryptutil.randomString(self.AUTH_KEY_LEN) file_obj, tmp = self._mktemp() try: file_obj.write(auth_key) # Must close the file before linking or renaming it on win32. file_obj.close() try: if hasattr(os, 'link') and sys.platform != 'cygwin': # because os.link works in some cygwin environments, # but returns errno 17 on others. Haven't figured out # how to predict when it will do that yet. os.link(tmp, self.auth_key_name) else: os.rename(tmp, self.auth_key_name) except OSError, why: if why[0] == EEXIST: auth_key = self.readAuthKey() if auth_key is None: # This should only happen if someone deletes # the auth key file out from under us. raise else: raise finally: file_obj.close() _removeIfPresent(tmp) return auth_key
def txn_getAuthKey(self): """Get the key for this consumer to use to sign its own communications. This function will create a new key if one does not yet exist. () -> str """ self.db_get_auth() val = self.cur.fetchone() if val is None: auth_key = cryptutil.randomString(self.AUTH_KEY_LEN) auth_key_s = self.blobEncode(auth_key) self.db_create_auth(auth_key_s) else: (auth_key_s,) = val auth_key = self.blobDecode(auth_key_s) if len(auth_key) != self.AUTH_KEY_LEN: fmt = 'Expected %d-byte string for auth key. Got %r' raise ValueError(fmt % (self.AUTH_KEY_LEN, auth_key)) return auth_key
def txn_getAuthKey(self): """Get the key for this consumer to use to sign its own communications. This function will create a new key if one does not yet exist. () -> str """ self.db_get_auth() val = self.cur.fetchone() if val is None: auth_key = cryptutil.randomString(self.AUTH_KEY_LEN) auth_key_s = self.blobEncode(auth_key) self.db_create_auth(auth_key_s) else: (auth_key_s, ) = val auth_key = self.blobDecode(auth_key_s) if len(auth_key) != self.AUTH_KEY_LEN: fmt = 'Expected %d-byte string for auth key. Got %r' raise ValueError(fmt % (self.AUTH_KEY_LEN, auth_key)) return auth_key
def getLPUser(self, lp_user): log.debug('Getting info about %s' % lp_user.name) # only call this if we have no info for a user member = launchpad.people[lp_user.name] openid_consumer = consumer.Consumer( dict(id=randomString(16, '0123456789abcdef')), None) openid_request = openid_consumer.begin("https://launchpad.net/~%s" % member.name) openid = openid_request.endpoint.getLocalID() lp_user.openids.append(openid) self.openids[openid] = lp_user try: lp_user.email = member.preferred_email_address.email except ValueError: pass for key in member.sshkeys: lp_user.ssh_keys.append( "%s %s %s" % (get_type(key.keytype), key.keytext, key.comment))
def registration(request, attribute_set='default', template_name='openid/registration_form.html'): """ Try to submit all the registration attributes for mojeID registration""" # Realm should be always something like 'https://example.org/openid/' realm = getattr(settings, 'MOJEID_REALM', request.build_absolute_uri(reverse(top))) user = OpenIDBackend.get_user_from_request(request) user_id = user.pk if user else None # Create Nonce nonce = Nonce(server_url=realm, user_id=user_id, timestamp=time.time(), salt=randomString(35, NONCE_CHARS)) nonce.save() fields = [] attributes = [x for x in get_attributes(attribute_set) if x.type == 'attribute'] # Append attributes to creation request if user is valid if user: for attribute in attributes: form_attr = attribute.registration_form_attrs_html(user_id) if form_attr: fields.append(form_attr) # Render the redirection template return render_to_response( template_name, { 'fields': fields, 'action': get_registration_url(), 'realm': realm, 'nonce': nonce.registration_nonce, }, context_instance=RequestContext(request) )
def generateHandle(n): return randomString(n, allowed_handle)
for (username, user_details) in users.items(): # accounts account_id = None if cur.execute("""select account_id from account_external_ids where external_id in (%s)""", ("username:%s" % username)): account_id = cur.fetchall()[0][0] # We have this bad boy - all we need to do is update his group membership else: # We need details member = launchpad.people[username] if not member.is_team: openid_consumer = consumer.Consumer(dict(id=randomString(16, '0123456789abcdef')), None) openid_request = openid_consumer.begin("https://launchpad.net/~%s" % member.name) user_details['openid_external_id'] = openid_request.endpoint.getLocalID() # Handle username change if cur.execute("""select account_id from account_external_ids where external_id in (%s)""", user_details['openid_external_id']): account_id = cur.fetchall()[0][0] cur.execute("""update account_external_ids set external_id=%s where external_id like 'username%%' and account_id = %s""", ('username:%s' % username, account_id)) else: user_details['ssh_keys'] = ["%s %s %s" % (get_type(key.keytype), key.keytext, key.comment) for key in member.sshkeys]
def makeCookie(): return randomString(32, string.letters + string.digits)
def __init__(self): self.server_assocs = {} self.nonces = {} self.auth_key = cryptutil.randomString(self.AUTH_KEY_LEN)
for (username, user_details) in users.items(): log.info('Syncing user: %s' % username) member = launchpad.people[username] # accounts account_id = None if cur.execute("""select account_id from account_external_ids where external_id in (%s)""", ("username:%s" % username)): account_id = cur.fetchall()[0][0] # We have this bad boy # all we need to do is update his group membership else: # We need details if not member.is_team: openid_consumer = consumer.Consumer( dict(id=randomString(16, '0123456789abcdef')), None) openid_request = openid_consumer.begin( "https://launchpad.net/~%s" % member.name) user_details['openid_external_id'] = \ openid_request.endpoint.getLocalID() # Handle username change if cur.execute("""select account_id from account_external_ids where external_id in (%s)""", user_details['openid_external_id']): account_id = cur.fetchall()[0][0] log.info('Handling username change id %s to %s' % (account_id, username)) cur.execute("""update account_external_ids set external_id = %s
def _createNonce(self): nonce = cryptutil.randomString(self.NONCE_LEN, self.NONCE_CHRS) self.store.storeNonce(nonce) return nonce
def process(self, **kw): session = getattr(request.session, 'openid_session', None) if not session: return set_cookie_and_redirect('/') oidconsumer = consumer.Consumer(session, self._store, consumer_class=GoogleAppsAwareConsumer) query = request.httprequest.args info = oidconsumer.complete(query, request.httprequest.base_url) display_identifier = info.getDisplayIdentifier() session['status'] = info.status if info.status == consumer.SUCCESS: dbname = session['dbname'] registry = RegistryManager.get(dbname) with registry.cursor() as cr: Modules = registry.get('ir.module.module') installed = Modules.search_count(cr, SUPERUSER_ID, ['&', ('name', '=', 'auth_openid'), ('state', '=', 'installed')]) == 1 if installed: Users = registry.get('res.users') #openid_url = info.endpoint.canonicalID or display_identifier openid_url = session['openid_url'] attrs = self._get_attributes_from_success_response(info) attrs['openid_url'] = openid_url session['attributes'] = attrs openid_email = attrs.get('email', False) domain = [] if openid_email: domain += ['|', ('openid_email', '=', False)] domain += [('openid_email', '=', openid_email)] domain += [('openid_url', '=', openid_url), ('active', '=', True)] ids = Users.search(cr, SUPERUSER_ID, domain) assert len(ids) < 2 if ids: user_id = ids[0] login = Users.browse(cr, SUPERUSER_ID, user_id).login key = randomString(utils.KEY_LENGTH, '0123456789abcdef') Users.write(cr, SUPERUSER_ID, [user_id], {'openid_key': key}) # TODO fill empty fields with the ones from sreg/ax cr.commit() return login_and_redirect(dbname, login, key) session['message'] = 'This OpenID identifier is not associated to any active users' elif info.status == consumer.SETUP_NEEDED: session['message'] = info.setup_url elif info.status == consumer.FAILURE and display_identifier: fmt = "Verification of %s failed: %s" session['message'] = fmt % (display_identifier, info.message) else: # FAILURE # Either we don't understand the code or there is no # openid_url included with the error. Give a generic # failure message. The library should supply debug # information in a log. session['message'] = 'Verification failed.' return set_cookie_and_redirect('/#action=login&loginerror=1')
def generateNonce(): return randomString(8, allowed_nonce)
def get_openid(lp_user): k = dict(id=randomString(16, '0123456789abcdef')) openid_consumer = consumer.Consumer(k, None) openid_request = openid_consumer.begin("https://launchpad.net/~%s" % lp_user) return openid_request.endpoint.getLocalID()
def show_decide_page(self, identity, username, openidreq): request = self.request _ = self._ if not request.user.valid or username != request.user.name: request.makeForbidden(403, _('''You need to manually go to your OpenID provider wiki and log in before you can use your OpenID. MoinMoin will never allow you to enter your password here. Once you have logged in, simply reload this page.''')) return request.theme.send_title(_("OpenID Trust verification"), pagename=request.page.page_name) # Start content (important for RTL support) request.write(request.formatter.startContent("content")) request.write(request.formatter.paragraph(1)) request.write(_('The site %s has asked for your identity.') % openidreq.trust_root) request.write(request.formatter.paragraph(0)) request.write(request.formatter.paragraph(1)) request.write(_(''' If you approve, the site represented by the trust root below will be told that you control the identity URL %s. (If you are using a delegated identity, the site will take care of reversing the delegation on its own.)''') % openidreq.identity) request.write(request.formatter.paragraph(0)) form = html.FORM(method='POST', action=request.page.url(request)) form.append(html.INPUT(type='hidden', name='action', value='serveopenid')) form.append(html.INPUT(type='hidden', name='openid.identity', value=openidreq.identity)) form.append(html.INPUT(type='hidden', name='openid.return_to', value=openidreq.return_to)) form.append(html.INPUT(type='hidden', name='openid.trust_root', value=openidreq.trust_root)) form.append(html.INPUT(type='hidden', name='openid.mode', value=openidreq.mode)) form.append(html.INPUT(type='hidden', name='name', value=username)) nonce = randomString(32, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') form.append(html.INPUT(type='hidden', name='nonce', value=nonce)) request.session['openidserver.nonce'] = nonce table = html.TABLE() form.append(table) tr = html.TR() table.append(tr) tr.append(html.TD().append(html.STRONG().append(html.Text(_('Trust root'))))) tr.append(html.TD().append(html.Text(openidreq.trust_root))) tr = html.TR() table.append(tr) tr.append(html.TD().append(html.STRONG().append(html.Text(_('Identity URL'))))) tr.append(html.TD().append(html.Text(identity))) tr = html.TR() table.append(tr) tr.append(html.TD().append(html.STRONG().append(html.Text(_('Name'))))) tr.append(html.TD().append(html.Text(username))) tr = html.TR() table.append(tr) tr.append(html.TD().append(html.STRONG().append(html.Text(_('Remember decision'))))) td = html.TD() tr.append(td) td.append(html.INPUT(type='checkbox', name='remember', value='yes')) td.append(html.Text(_('Remember this trust decision and don\'t ask again'))) tr = html.TR() table.append(tr) tr.append(html.TD()) td = html.TD() tr.append(td) td.append(html.INPUT(type='submit', name='approve', value=_("Approve"))) td.append(html.INPUT(type='submit', name='dontapprove', value=_("Don't approve"))) request.write(unicode(form)) request.write(request.formatter.endContent()) request.theme.send_footer(request.page.page_name) request.theme.send_closing_html()
log.info('Syncing user: %s' % username) member = launchpad.people[username] # accounts account_id = None if cur.execute( """select account_id from account_external_ids where external_id in (%s)""", ("username:%s" % username)): account_id = cur.fetchall()[0][0] # We have this bad boy # all we need to do is update his group membership else: # We need details if not member.is_team: openid_consumer = consumer.Consumer( dict(id=randomString(16, '0123456789abcdef')), None) openid_request = openid_consumer.begin( "https://launchpad.net/~%s" % member.name) user_details['openid_external_id'] = \ openid_request.endpoint.getLocalID() # Handle username change if cur.execute( """select account_id from account_external_ids where external_id in (%s)""", user_details['openid_external_id']): account_id = cur.fetchall()[0][0] log.info('Handling username change id %s to %s' % (account_id, username)) cur.execute( """update account_external_ids
def get_openid(lp_user): k = dict(id=randomString(16, '0123456789abcdef')) openid_consumer = consumer.Consumer(k, None) openid_request = openid_consumer.begin( "https://launchpad.net/~%s" % lp_user) return openid_request.endpoint.getLocalID()
def process(self, req, **kw): session = getattr(req.session, "openid_session", None) if not session: return set_cookie_and_redirect(req, "/") oidconsumer = consumer.Consumer(session, self._store, consumer_class=GoogleAppsAwareConsumer) query = req.httprequest.args info = oidconsumer.complete(query, req.httprequest.base_url) display_identifier = info.getDisplayIdentifier() session["status"] = info.status if info.status == consumer.SUCCESS: dbname = session["dbname"] registry = RegistryManager.get(dbname) with registry.cursor() as cr: Modules = registry.get("ir.module.module") installed = ( Modules.search_count( cr, SUPERUSER_ID, ["&", ("name", "=", "auth_openid"), ("state", "=", "installed")] ) == 1 ) if installed: Users = registry.get("res.users") # openid_url = info.endpoint.canonicalID or display_identifier openid_url = session["openid_url"] attrs = self._get_attributes_from_success_response(info) attrs["openid_url"] = openid_url session["attributes"] = attrs openid_email = attrs.get("email", False) domain = [] if openid_email: domain += ["|", ("openid_email", "=", False)] domain += [("openid_email", "=", openid_email)] domain += [("openid_url", "=", openid_url), ("active", "=", True)] ids = Users.search(cr, SUPERUSER_ID, domain) assert len(ids) < 2 if ids: user_id = ids[0] login = Users.browse(cr, SUPERUSER_ID, user_id).login key = randomString(utils.KEY_LENGTH, "0123456789abcdef") Users.write(cr, SUPERUSER_ID, [user_id], {"openid_key": key}) # TODO fill empty fields with the ones from sreg/ax cr.commit() return login_and_redirect(req, dbname, login, key) session["message"] = "This OpenID identifier is not associated to any active users" elif info.status == consumer.SETUP_NEEDED: session["message"] = info.setup_url elif info.status == consumer.FAILURE and display_identifier: fmt = "Verification of %s failed: %s" session["message"] = fmt % (display_identifier, info.message) else: # FAILURE # Either we don't understand the code or there is no # openid_url included with the error. Give a generic # failure message. The library should supply debug # information in a log. session["message"] = "Verification failed." return set_cookie_and_redirect(req, "/#action=login&loginerror=1")