def testGetLoginMethods(self): """ Test L{userbase.getLoginMethods} """ dbdir = FilePath(self.mktemp()) s = Store(dbdir) ls = userbase.LoginSystem(store=s) dependency.installOn(ls, s) acc = ls.addAccount('username', 'dom.ain', 'password', protocol='speech') ss = acc.avatars.open() for protocol in (None, 'speech'): self.assertEqual(list(userbase.getAccountNames(ss, protocol)), [('username', 'dom.ain')]) # defaults to ANY_PROTOCOL acc.addLoginMethod('username2', 'dom.ain') # check that searching for protocol=speech also gives us the # ANY_PROTOCOL LoginMethod for protocol in (None, 'speech'): self.assertEqual(sorted(userbase.getAccountNames(ss, protocol)), [('username', 'dom.ain'), ('username2', 'dom.ain')])
def fromSharedItem(cls, sharedItem): """ Return an instance of C{cls} derived from the given L{Item} that has been shared. Note that this API does not provide any guarantees of which result it will choose. If there are are multiple possible return values, it will select and return only one. Items may be shared under multiple L{shareID}s. A user may have multiple valid account names. It is sometimes impossible to tell from context which one is appropriate, so if your application has another way to select a specific shareID you should use that instead. @param sharedItem: an L{Item} that should be shared. @return: an L{Identifier} describing the C{sharedItem} parameter. @raise L{NoSuchShare}: if the given item is not shared or its store does not contain any L{LoginMethod} items which would identify a user. """ localpart = None for (localpart, domain) in userbase.getAccountNames(sharedItem.store): break if localpart is None: raise NoSuchShare() for share in sharedItem.store.query(Share, Share.sharedItem == sharedItem): break else: raise NoSuchShare() return cls( shareID=share.shareID, localpart=localpart, domain=domain)
def cb(xxx_todo_changeme1): (interface, avatar, logout) = xxx_todo_changeme1 ss = avatar.avatars.open() self.assertEqual(list(userbase.getAccountNames(ss)), [('alice', 'localhost')]) self.assertEqual(avatar.password, SECRET) logout()
def produceResource(self, request, segments, webViewer): """ Produce a resource that traverses site-wide content, passing down the given webViewer. This delegates to the site store's L{IMantissaSite} adapter, to avoid a conflict with the L{ISiteRootPlugin} interface. This method will typically be given an L{_AuthenticatedWebViewer}, which can build an appropriate resource for an authenticated shell page, whereas the site store's L{IWebViewer} adapter would show an anonymous page. The result of this method will be a L{_CustomizingResource}, to provide support for resources which may provide L{ICustomizable}. Note that Mantissa itself no longer implements L{ICustomizable} anywhere, though. All application code should phase out inspecting the string passed to ICustomizable in favor of getting more structured information from the L{IWebViewer}. However, it has not been deprecated yet because the interface which allows application code to easily access the L{IWebViewer} from view code has not yet been developed; it is forthcoming. See ticket #2707 for progress on this. """ mantissaSite = self.publicSiteRoot if mantissaSite is not None: for resource, domain in userbase.getAccountNames(self.store): username = '******' % (resource, domain) break else: username = None bottomResource, newSegments = mantissaSite.siteProduceResource( request, segments, webViewer) return (_CustomizingResource(bottomResource, username), newSegments) return None
def fromSharedItem(cls, sharedItem): """ Return an instance of C{cls} derived from the given L{Item} that has been shared. Note that this API does not provide any guarantees of which result it will choose. If there are are multiple possible return values, it will select and return only one. Items may be shared under multiple L{shareID}s. A user may have multiple valid account names. It is sometimes impossible to tell from context which one is appropriate, so if your application has another way to select a specific shareID you should use that instead. @param sharedItem: an L{Item} that should be shared. @return: an L{Identifier} describing the C{sharedItem} parameter. @raise L{NoSuchShare}: if the given item is not shared or its store does not contain any L{LoginMethod} items which would identify a user. """ localpart = None for (localpart, domain) in userbase.getAccountNames(sharedItem.store): break if localpart is None: raise NoSuchShare() for share in sharedItem.store.query(Share, Share.sharedItem == sharedItem): break else: raise NoSuchShare() return cls(shareID=share.shareID, localpart=localpart, domain=domain)
def test_buildTerminalProtocol(self): """ L{ImaginaryApp.buildTerminalProtocol} returns a L{CharacterSelectionTextServer} instance with a role representing the store it is in, a reference to the L{ImaginaryWorld} installed on the Imaginary application store, and a list of L{Thing} items shared to the role. """ # XXX This is too many stores for a unit test to need to create. siteStore = Store(filesdir=FilePath(self.mktemp())) Mantissa().installSite(siteStore, u'example.com', u'', False) installOffering(siteStore, imaginaryOffering, {}) login = siteStore.findUnique(LoginSystem) account = login.addAccount(u'alice', u'example.com', u'password') userStore = account.avatars.open() app = ImaginaryApp(store=userStore) installOn(app, userStore) imaginary = login.accountByAddress(u'Imaginary', None).avatars.open() world = imaginary.findUnique(ImaginaryWorld) # Alice connects to her own ImaginaryApp (all that is possible at the # moment). viewer = _AuthenticatedShellViewer(getAccountNames(userStore)) proto = app.buildTerminalProtocol(viewer) self.assertIdentical(proto.world, world) self.assertEqual(proto.role.externalID, u'*****@*****.**') self.assertEqual(proto.choices, [])
def testAccountNames(self): dbdir = self.mktemp() s = Store(dbdir) ls = userbase.LoginSystem(store=s) ls.installOn(s) acc = ls.addAccount('username', 'dom.ain', 'password') ss = acc.avatars.open() self.assertEquals(list(userbase.getAccountNames(ss)), [('username', 'dom.ain')]) acc.addLoginMethod(u'nameuser', u'ain.dom') names = list(userbase.getAccountNames(ss)) names.sort() self.assertEquals(names, [('nameuser', 'ain.dom'), ('username', 'dom.ain')])
def _getUsername(self): """ Return a localpart@domain style string naming the owner of our store. @rtype: C{unicode} """ for (l, d) in getAccountNames(self.store): return l + u'@' + d
def __init__(self, original): for resource, domain in userbase.getAccountNames(original.installedOn): username = '******' % (resource, domain) break else: username = None PublicPage.__init__(self, original, original.store.parent, getLoader('initialize'), IStaticShellContent(original.installedOn, None), username)
def validateFrom(self, helo, origin): """ Verify that the given origin address is one this user is allowed to claim. """ for local, domain in userbase.getAccountNames(self.avatar.store): if local == origin.local and domain == origin.domain: self.origin = origin return defer.succeed(origin) return defer.fail(smtp.SMTPBadSender(origin))
def testAccountNames(self): dbdir = FilePath(self.mktemp()) s = Store(dbdir) ls = userbase.LoginSystem(store=s) dependency.installOn(ls, s) acc = ls.addAccount('username', 'dom.ain', 'password') ss = acc.avatars.open() self.assertEqual( list(userbase.getAccountNames(ss)), [('username', 'dom.ain')]) acc.addLoginMethod('nameuser', 'ain.dom') names = list(userbase.getAccountNames(ss)) names.sort() self.assertEqual( names, [('nameuser', 'ain.dom'), ('username', 'dom.ain')])
def cmd_whoami(self, source): """ Find out who you are authenticated as. """ nickname = source.user.nickname try: avatar = source.protocol.getAuthenticatedAvatar(nickname) username, domain = getAccountNames(avatar.store).next() msg = u'Authenticated as "%s@%s".' % (username, domain) except errors.AuthenticationError: msg = u'Not authenticated.' source.reply(msg)
def requestAppointmentWith(self, whom, when): appointment = Appointment( store=self.store, when=when, withWhomShareID=whom.shareID, withWhomUsername=whom.localpart, withWhomDomain=whom.domain) role = getPrimaryRole(self.store, u"%s@%s" % (whom.localpart, whom.domain), True) appointmentID = role.shareItem(appointment, interfaces=[IMessageReceiver]).shareID messenger = AMPMessenger( self.messageQueue, Identifier(appointmentID, *getAccountNames(self.store).next()), whom) messenger.messageRemote( MakeAppointment, appointment, when=when.asISO8601TimeAndDate())
def switchTo(self, app): """ Use the given L{ITerminalServerFactory} to create a new L{ITerminalProtocol} and connect it to C{self.terminal} (such that it cannot actually disconnect, but can do most anything else). Control of the terminal is delegated to it until it gives up that control by disconnecting itself from the terminal. @type app: L{ITerminalServerFactory} provider @param app: The factory which will be used to create a protocol instance. """ viewer = _AuthenticatedShellViewer(list(getAccountNames(self._store))) self._protocol = app.buildTerminalProtocol(viewer) self._protocol.makeConnection(_ReturnToMenuWrapper(self, self.terminal))
def lookupProcessor(self, msg, dialogs): if isinstance(msg, sip.Request) and msg.method == "REGISTER": #not our dept return defer.succeed(None) for name, domain in userbase.getAccountNames(self.store, protocol=u'sip'): if name == sip.parseAddress(msg.headers["to"][0])[1].username: contact = sip.IContact(self.store) def regged(_): return defer.succeed(None) def unregged(e): self.uas.dialogs = dialogs return self.uas return defer.maybeDeferred(contact.getRegistrationInfo, sip.parseAddress(msg.headers["from"][0])[1]).addCallbacks(regged, unregged) else: return defer.succeed(None)
def renderHTTP(self, ctx): """ Handle the password reset form. The following exchange describes the process: S: Render C{reset} C: POST C{username} or C{email} S: L{handleRequestForUser}, render C{reset-check-email} (User follows the emailed reset link) S: Render C{reset-step-two} C: POST C{password1} S: L{resetPassword}, render C{reset-done} """ req = inevow.IRequest(ctx) if req.method == 'POST': if req.args.get('username', [''])[0]: user = unicode(usernameFromRequest(req), 'ascii') self.handleRequestForUser(user, URL.fromContext(ctx)) self.fragment = self.templateResolver.getDocFactory( 'reset-check-email') elif req.args.get('email', [''])[0]: email = req.args['email'][0].decode('ascii') acct = self.accountByAddress(email) if acct is not None: username = '******'.join( userbase.getAccountNames(acct.avatars.open()).next()) self.handleRequestForUser(username, URL.fromContext(ctx)) self.fragment = self.templateResolver.getDocFactory( 'reset-check-email') elif 'password1' in req.args: (password, ) = req.args['password1'] self.resetPassword(self.attempt, unicode(password)) self.fragment = self.templateResolver.getDocFactory( 'reset-done') else: # Empty submit; redirect back to self return URL.fromContext(ctx) elif self.attempt: self.fragment = self.templateResolver.getDocFactory( 'reset-step-two') return PublicPage.renderHTTP(self, ctx)
def renderHTTP(self, ctx): """ Handle the password reset form. The following exchange describes the process: S: Render C{reset} C: POST C{username} or C{email} S: L{handleRequestForUser}, render C{reset-check-email} (User follows the emailed reset link) S: Render C{reset-step-two} C: POST C{password1} S: L{resetPassword}, render C{reset-done} """ req = inevow.IRequest(ctx) if req.method == 'POST': if req.args.get('username', [''])[0]: user = unicode(usernameFromRequest(req), 'ascii') self.handleRequestForUser(user, URL.fromContext(ctx)) self.fragment = self.templateResolver.getDocFactory( 'reset-check-email') elif req.args.get('email', [''])[0]: email = req.args['email'][0].decode('ascii') acct = self.accountByAddress(email) if acct is not None: username = '******'.join( userbase.getAccountNames(acct.avatars.open()).next()) self.handleRequestForUser(username, URL.fromContext(ctx)) self.fragment = self.templateResolver.getDocFactory('reset-check-email') elif 'password1' in req.args: (password,) = req.args['password1'] self.resetPassword(self.attempt, unicode(password)) self.fragment = self.templateResolver.getDocFactory('reset-done') else: # Empty submit; redirect back to self return URL.fromContext(ctx) elif self.attempt: self.fragment = self.templateResolver.getDocFactory('reset-step-two') return PublicPage.renderHTTP(self, ctx)
def buildWorld(testCase): """ Build a L{TestWorld}. """ # XXX This is too many stores for a unit test to need to create. siteStore = Store(filesdir=FilePath(testCase.mktemp())) Mantissa().installSite(siteStore, u'example.com', u'', False) installOffering(siteStore, imaginaryOffering, {}) login = siteStore.findUnique(LoginSystem) account = login.addAccount(u'alice', u'example.com', u'password') userStore = account.avatars.open() app = ImaginaryApp(store=userStore) installOn(app, userStore) imaginary = login.accountByAddress(u'Imaginary', None).avatars.open() world = imaginary.findUnique(ImaginaryWorld) # Alice connects to her own ImaginaryApp (all that is possible at the # moment). viewer = _AuthenticatedShellViewer(getAccountNames(userStore)) return TestWorld(proto=app.buildTerminalProtocol(viewer), world=world)
def activate(self): username, domain = userbase.getAccountNames(self.store).next() self.username = ("%s@%s" % (username, domain)).encode('ascii') self.lib = dspam.startDSPAM(self.username, self._homePath().path.encode('ascii'))
def getSelfRole(store): """ Retrieve the Role which corresponds to the user to whom the given store belongs. """ return getAccountRole(store, userbase.getAccountNames(store))
def localElementByName(self, n): for name, domain in userbase.getAccountNames(self.store, protocol=u'sip'): #if we got here, we have a SIP account... return useragent.ICallControllerFactory(self.store)
def _getUsername(self): """ Return a username, suitable for creating a L{VirtualHostWrapper} with. """ return u'@'.join(getAccountNames(self.store).next())
def _username(self): for (localpart, domain) in userbase.getAccountNames(self.store): return (localpart + "@" + domain).encode("utf-8")
def cb((interface, avatar, logout)): ss = avatar.avatars.open() self.assertEquals(list(userbase.getAccountNames(ss)), [(u'alice', u'localhost')]) self.assertEquals(avatar.password, SECRET) logout()
def _username(self): for (localpart, domain) in userbase.getAccountNames(self.store): return (localpart + '@' + domain).encode('utf-8')