def presenceReceived(self, cnx, prs): '''Presence received from a registered user. If any presence stanza is received from an unregistered user, don't even look at it. They should register first.''' frm = prs.getFrom() user = UserAccount(frm) if not user.isRegistered(): return #TODO: Send a registration-required error resource = frm.getResource() to = prs.getTo().getStripped() typ = prs.getType() if typ == 'subscribe': cnx.send(Presence(typ='subscribed', frm=to, to=user.jid)) self.sendBitcoinPresence(cnx, user) elif typ == 'subscribed': debug('We were allowed to see %s\'s presence.' % user) elif typ == 'unsubscribe': debug('Just received an "unsubscribe" presence stanza. What does that mean?') elif typ == 'unsubscribed': debug('Unsubscribed. Any interest in this information?') elif typ == 'probe': self.sendBitcoinPresence(cnx, user) elif (typ == 'available') or (typ is None): self.userResourceConnects(user, resource) elif typ == 'unavailable': self.userResourceDisconnects(user, resource) elif typ == 'error': debug('Presence error. TODO: Handle it by not sending presence updates to them until they send a non-error.') raise NodeProcessed
def discoReceived(self, user, what, node): if 'info' == what: if node is None: ids = [{'category': 'gateway', 'type': 'bitcoin', 'name':LIB_DESCRIPTION}] return {'ids': ids, 'features': [NS_DISCO_INFO, NS_DISCO_ITEMS, NS_REGISTER, NS_VERSION, NS_GATEWAY, NS_LAST]} elif 'users' == node: ids = [{'category': 'directory', 'type': 'user', 'name': _(DISCO, 'user_list')}] return {'ids': ids, 'features': [NS_DISCO_INFO, NS_DISCO_ITEMS]} elif 'items' == what: items = [] if user.isRegistered(): if node is None: items.append({'jid': user.getLocalJID(), 'name': _(DISCO, 'your_addresses'), 'node': 'addresses'}) else: items.append({'jid': self.jid, 'name': LIB_DESCRIPTION}) if user.isAdmin(): if node is None: items.append({'jid': self.jid, 'name': 'Users', 'node': 'users'}) elif 'users' == node: for jid in UserAccount.getAllMembers(): member = UserAccount(JID(jid)) name = member.username items.append({'jid': member.getLocalJID(), 'name': name}) return items
def test_account_exists(self): self.new_account.save_user_details() test_newaccount = UserAccount("Gmail", "User", "Password") test_newaccount.save_user_details() account_exists = UserAccount.check_user_account("Gmail") self.assertTrue(account_exists)
def unregistrationRequested(self, iq): '''An unregistration request was received''' user = UserAccount(iq.getFrom()) info("Unegistration request from %s" % user) try: user.unregister() except UnknownUserError: pass # We don't really mind about unknown people wanting to unregister. Should we? self.send(iq.buildReply('result')) self.send(Presence(to=user.jid, frm=self.jid, typ='unsubscribe')) self.send(Presence(to=user.jid, frm=self.jid, typ='unsubscribed')) self.send(Presence(to=user.jid, frm=self.jid, typ='unavailable', status=_(REGISTRATION, 'bye')))
def start(self, proxy=None): if not self.connect(None, proxy): raise Exception(_('Console', 'cannot_connect').format(server=self.Server, port=self.Port)) if not self.auth(self.jid, self.password): raise Exception(_('Console', 'cannot_auth').format(jid=self.jid)) self._RegisterHandlers() debug("Sending initial presence to all contacts...") for jid in UserAccount.getAllMembers(): self.send(Presence(to=jid, frm=self.jid, typ='probe')) user = UserAccount(JID(jid)) self.sendBitcoinPresence(self, user) for addr in user.getRoster(): Address(JID(addr)).sendBitcoinPresence(self, user)
def test_delete_user_account(self): self.new_account.save_user_details() test_newaccount = UserAccount("Gmail", "User", "Password") test_newaccount = save_user_details() self.new_account.delete_user_details() self.assertEqual(len(UserAccount.user_pass_list), 1)
def registrationRequested(self, iq): '''A registration request was received. If an invalid username is choosen, the whole registration fails. Also, although it's normally impossible, we're being paranoid and forbid registrations from JIDs that don't contain a dot, since they might conflict with usernames. ''' frm = iq.getFrom() info("Registration request from %s" % frm) if -1 == frm.getStripped().find('.'): reply = iq.buildReply(typ='error') reply.addChild(node=ErrorNode('not-acceptable', 500, 'cancel', _(REGISTRATION, 'error_invalid_jid'))) self.send(reply) warning("Possible hacking attempt: JID '%s' (no dot!) tried to register to the gateway." % frm.getStripped()) return isUpdate = False user = UserAccount(frm) requestedUsername = '' for child in iq.getQueryChildren(): if 'username' == child.getName(): requestedUsername = child.getData() break try: user.username = requestedUsername info("%s changed username to '%s'" % (user, user.username)) except UsernameNotAvailableError: if 0 == len(requestedUsername): msg = 'error_missing_username' else: msg = 'error_invalid_username' reply = iq.buildReply(typ='error') reply.addChild(node=ErrorNode('not-acceptable', 406, 'modify', _(REGISTRATION, msg))) self.send(reply) return try: user.register() new_address = user.createAddress() self.addAddressToRoster(new_address, user) except AlreadyRegisteredError: info("(actually just an update)") isUpdate = True self.send(Iq(typ='result', to=frm, frm=self.jid, attrs={'id': iq.getID()})) if not isUpdate: self.send(Presence(typ='subscribe', to=frm.getStripped(), frm=self.jid))
def messageReceived(self, cnx, msg): '''Message received, addressed to the component. The command execution can raise exceptions, but those will be taken care of by the caller (messageHandler())''' user = UserAccount(msg.getFrom()) if user.isRegistered(): try: address = Address(msg.getBody()) msg = Message(to=msg.getFrom(), frm=address.jid,\ body=_(ROSTER, 'address_start_chat').format(address=address), typ='chat') except InvalidBitcoinAddressError: (action, args) = parseCommand(msg.getBody()) if action is None: return msg = msg.buildReply(Command(action, args).execute(user)) msg.setType('chat') if user.checkBalance() is not None: self.sendBitcoinPresence(cnx, user) else: error = _(REGISTRATION, 'error_not_registered') msg = msg.buildReply(_(COMMANDS, 'error_message').format(message=error)) msg.setType('error') cnx.send(msg) raise NodeProcessed
def iqReceived(self, cnx, iq): '''IQ handler for the component''' typ = iq.getType() queries = iq.getChildren() # there should be only one if 0 == len(queries): return ns = queries[0].getNamespace() debug("OK we're handling IQ %s, ns=%s" % (typ, ns)) if NS_REGISTER == ns: if 'set' == typ: children = iq.getQueryChildren() if (0 != len(children)) and ('remove' == children[0].getName()): self.unregistrationRequested(iq) else: self.registrationRequested(iq) raise NodeProcessed elif 'get' == typ: instructions = Node('instructions') username = Node('username') user = UserAccount(iq.getFrom()) registered = user.isRegistered() if registered: instructions.setData(_(REGISTRATION, 'set_username')) username.setData(user.username) else: debug("A new user is preparing a registration") instructions.setData(_(REGISTRATION, 'introduction')) reply = iq.buildReply('result') query = reply.getQuery() if registered: query.addChild('registered') query.addChild(node=instructions) query.addChild(node=username) cnx.send(reply) raise NodeProcessed else: # Unkown namespace and type. The default handler will take care of it if we don't raise NodeProcessed. debug("Unknown IQ with ns '%s' and type '%s'." % (ns, typ)) elif NS_GATEWAY == ns: if 'get' == typ: reply = iq.buildReply('result') query = reply.getQuery() query.addChild('desc', payload=[_(ROSTER, 'address2jid_description')]) query.addChild('prompt', payload=[_(ROSTER, 'address2jid_prompt')]) cnx.send(reply) raise NodeProcessed elif 'set' == typ: children = iq.getQueryChildren() if (0 != len(children)) and ('prompt' == children[0].getName()): prompt = children[0].getData() debug("Someone wants to convert %s into a JID" % prompt) jid = Node('jid') try: jid.setData(Address(prompt).jid) except InvalidBitcoinAddressError: try: jid.setData(UserAccount(prompt).getLocalJID()) except UnknownUserError: reply = iq.buildReply(typ='error') reply.addChild(node=ErrorNode('item-not-found', 404, 'cancel', _(ROSTER, 'address2jid_invalid'))) cnx.send(reply) raise NodeProcessed reply = iq.buildReply('result') query = reply.getQuery() query.addChild(node=jid) cnx.send(reply) raise NodeProcessed elif NS_VCARD == ns: if 'get' == typ: reply = iq.buildReply('result') query = reply.getQuery() query.addChild('FN', payload=["%s v%s" % (LIB_NAME, LIB_VERSION)]) query.addChild('DESC', payload=[LIB_DESCRIPTION]) cnx.send(reply) raise NodeProcessed Addressable.iqReceived(self, cnx, iq)
def setUp(self): self.new_account = UserAccount("Gmail", "*****@*****.**", "password123")
def show_account_credentials(): return UserAccount.show_user_details()
def test_show_account_details(self): self.assertEqual(UserAccount.show_user_details(), UserAccount.user_pass_list)
class UserAccountTest(unittest.TestCase): def setUp(self): self.new_account = UserAccount("Gmail", "*****@*****.**", "password123") def tearDown(self): UserAccount.user_pass_list = [] def test_init(self): self.assertEqual(self.new_account.account, "Gmail") self.assertEqual(self.new_account.email, "*****@*****.**") self.assertEqual(sel.new_account.password, "password123") def test_save_user(self): self.new_account.save_user_details() self.assertEqual(len(UserAccount.user_pass_list), 1) def test_saving_multiple_accounts(self): self.new_account.save_user_details() test_newaccount = UserAccount("Gmail", "User", "Password") test_newaccount.save_user_details() self.assertEqual(len(UserAccount.user_pass_list), 2) def test_delete_user_account(self): self.new_account.save_user_details() test_newaccount = UserAccount("Gmail", "User", "Password") test_newaccount = save_user_details() self.new_account.delete_user_details() self.assertEqual(len(UserAccount.user_pass_list), 1) def test_search_user_account(self): self.new_account.save_user_details() test_newaccount = UserAccount("Gmail", "User", "Password") test_newaccount = save_user_details() search_user = UserAccount.search_user_account("Facebook") self.assertEqual(search_user.account, test_newaccount.account) def test_account_exists(self): self.new_account.save_user_details() test_newaccount = UserAccount("Gmail", "User", "Password") test_newaccount.save_user_details() account_exists = UserAccount.check_user_account("Gmail") self.assertTrue(account_exists) def test_show_account_details(self): self.assertEqual(UserAccount.show_user_details(), UserAccount.user_pass_list) def test_copy_pwd(self): self.new_account.save_user_details() UserAccount.copy_pwd("password123") self.assertEqual(self.new_account.password, pyperclip.paste())
def test_search_user_account(self): self.new_account.save_user_details() test_newaccount = UserAccount("Gmail", "User", "Password") test_newaccount = save_user_details() search_user = UserAccount.search_user_account("Facebook") self.assertEqual(search_user.account, test_newaccount.account)
def test_saving_multiple_accounts(self): self.new_account.save_user_details() test_newaccount = UserAccount("Gmail", "User", "Password") test_newaccount.save_user_details() self.assertEqual(len(UserAccount.user_pass_list), 2)
def search_account(account): return UserAccount.search_user_account(account)
def test_copy_pwd(self): self.new_account.save_user_details() UserAccount.copy_pwd("password123") self.assertEqual(self.new_account.password, pyperclip.paste())
def create_user_details(account,email,password): new_account = UserAccount(account,email,password) return new_account