comparison sat/plugins/plugin_xep_0077.py @ 2562:26edcf3a30eb

core, setup: huge cleaning: - moved directories from src and frontends/src to sat and sat_frontends, which is the recommanded naming convention - move twisted directory to root - removed all hacks from setup.py, and added missing dependencies, it is now clean - use https URL for website in setup.py - removed "Environment :: X11 Applications :: GTK", as wix is deprecated and removed - renamed sat.sh to sat and fixed its installation - added python_requires to specify Python version needed - replaced glib2reactor which use deprecated code by gtk3reactor sat can now be installed directly from virtualenv without using --system-site-packages anymore \o/
author Goffi <goffi@goffi.org>
date Mon, 02 Apr 2018 19:44:50 +0200
parents src/plugins/plugin_xep_0077.py@0046283a285d
children 56f94936df1e
comparison
equal deleted inserted replaced
2561:bd30dc3ffe5a 2562:26edcf3a30eb
1 #!/usr/bin/env python2
2 # -*- coding: utf-8 -*-
3
4 # SAT plugin for managing xep-0077
5 # Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 from sat.core.i18n import _
21 from sat.core.constants import Const as C
22 from sat.core import exceptions
23 from sat.core.log import getLogger
24 log = getLogger(__name__)
25 from twisted.words.protocols.jabber import jid
26 from twisted.words.protocols.jabber import xmlstream
27 from twisted.internet import defer, reactor
28 from sat.tools import xml_tools
29
30 from wokkel import data_form
31
32 NS_REG = 'jabber:iq:register'
33
34 PLUGIN_INFO = {
35 C.PI_NAME: "XEP 0077 Plugin",
36 C.PI_IMPORT_NAME: "XEP-0077",
37 C.PI_TYPE: "XEP",
38 C.PI_PROTOCOLS: ["XEP-0077"],
39 C.PI_DEPENDENCIES: [],
40 C.PI_MAIN: "XEP_0077",
41 C.PI_DESCRIPTION: _("""Implementation of in-band registration""")
42 }
43
44 # FIXME: this implementation is incomplete
45
46 class RegisteringAuthenticator(xmlstream.ConnectAuthenticator):
47 # FIXME: request IQ is not send to check available fields, while XEP recommand to use it
48 # FIXME: doesn't handle data form or oob
49
50 def __init__(self, jid_, password, email=None):
51 xmlstream.ConnectAuthenticator.__init__(self, jid_.host)
52 self.jid = jid_
53 self.password = password
54 self.email = email
55 self.registered = defer.Deferred()
56 log.debug(_(u"Registration asked for {jid}").format(
57 jid = jid_))
58
59 def connectionMade(self):
60 log.debug(_(u"Connection made with {server}".format(server=self.jid.host)))
61 self.xmlstream.otherEntity = jid.JID(self.jid.host)
62 self.xmlstream.namespace = C.NS_CLIENT
63 self.xmlstream.sendHeader()
64
65 iq = XEP_0077.buildRegisterIQ(self.xmlstream, self.jid, self.password, self.email)
66 d = iq.send(self.jid.host).addCallbacks(self.registrationCb, self.registrationEb)
67 d.chainDeferred(self.registered)
68
69 def registrationCb(self, answer):
70 log.debug(_(u"Registration answer: {}").format(answer.toXml()))
71 self.xmlstream.sendFooter()
72
73 def registrationEb(self, failure_):
74 log.info(_("Registration failure: {}").format(unicode(failure_.value)))
75 self.xmlstream.sendFooter()
76 raise failure_
77
78
79 class XEP_0077(object):
80
81 def __init__(self, host):
82 log.info(_("Plugin XEP_0077 initialization"))
83 self.host = host
84 host.bridge.addMethod("inBandRegister", ".plugin", in_sign='ss', out_sign='',
85 method=self._inBandRegister,
86 async=True)
87 host.bridge.addMethod("inBandAccountNew", ".plugin", in_sign='ssssi', out_sign='',
88 method=self._registerNewAccount,
89 async=True)
90 host.bridge.addMethod("inBandUnregister", ".plugin", in_sign='ss', out_sign='',
91 method=self._unregister,
92 async=True)
93 host.bridge.addMethod("inBandPasswordChange", ".plugin", in_sign='ss', out_sign='',
94 method=self._changePassword,
95 async=True)
96
97 @staticmethod
98 def buildRegisterIQ(xmlstream_, jid_, password, email=None):
99 iq_elt = xmlstream.IQ(xmlstream_, 'set')
100 iq_elt["to"] = jid_.host
101 query_elt = iq_elt.addElement(('jabber:iq:register', 'query'))
102 username_elt = query_elt.addElement('username')
103 username_elt.addContent(jid_.user)
104 password_elt = query_elt.addElement('password')
105 password_elt.addContent(password)
106 if email is not None:
107 email_elt = query_elt.addElement('email')
108 email_elt.addContent(email)
109 return iq_elt
110
111 def _regCb(self, answer, client, post_treat_cb):
112 """Called after the first get IQ"""
113 try:
114 query_elt = answer.elements(NS_REG, 'query').next()
115 except StopIteration:
116 raise exceptions.DataError("Can't find expected query element")
117
118 try:
119 x_elem = query_elt.elements(data_form.NS_X_DATA, 'x').next()
120 except StopIteration:
121 # XXX: it seems we have an old service which doesn't manage data forms
122 log.warning(_("Can't find data form"))
123 raise exceptions.DataError(_("This gateway can't be managed by SàT, sorry :("))
124
125 def submitForm(data, profile):
126 form_elt = xml_tools.XMLUIResultToElt(data)
127
128 iq_elt = client.IQ()
129 iq_elt['id'] = answer['id']
130 iq_elt['to'] = answer['from']
131 query_elt = iq_elt.addElement("query", NS_REG)
132 query_elt.addChild(form_elt)
133 d = iq_elt.send()
134 d.addCallback(self._regSuccess, client, post_treat_cb)
135 d.addErrback(self._regFailure, client)
136 return d
137
138 form = data_form.Form.fromElement(x_elem)
139 submit_reg_id = self.host.registerCallback(submitForm, with_data=True, one_shot=True)
140 return xml_tools.dataForm2XMLUI(form, submit_reg_id)
141
142 def _regEb(self, failure, client):
143 """Called when something is wrong with registration"""
144 log.info(_("Registration failure: %s") % unicode(failure.value))
145 raise failure
146
147 def _regSuccess(self, answer, client, post_treat_cb):
148 log.debug(_(u"registration answer: %s") % answer.toXml())
149 if post_treat_cb is not None:
150 post_treat_cb(jid.JID(answer['from']), client.profile)
151 return {}
152
153 def _regFailure(self, failure, client):
154 log.info(_(u"Registration failure: %s") % unicode(failure.value))
155 if failure.value.condition == 'conflict':
156 raise exceptions.ConflictError( _("Username already exists, please choose an other one"))
157 raise failure
158
159 def _inBandRegister(self, to_jid_s, profile_key=C.PROF_KEY_NONE):
160 return self.inBandRegister, jid.JID(to_jid_s, profile_key)
161
162 def inBandRegister(self, to_jid, post_treat_cb=None, profile_key=C.PROF_KEY_NONE):
163 """register to a service
164
165 @param to_jid(jid.JID): jid of the service to register to
166 """
167 # FIXME: this post_treat_cb arguments seems wrong, check it
168 client = self.host.getClient(profile_key)
169 log.debug(_(u"Asking registration for {}").format(to_jid.full()))
170 reg_request = client.IQ(u'get')
171 reg_request["from"] = client.jid.full()
172 reg_request["to"] = to_jid.full()
173 reg_request.addElement('query', NS_REG)
174 d = reg_request.send(to_jid.full()).addCallbacks(self._regCb, self._regEb, callbackArgs=[client, post_treat_cb], errbackArgs=[client])
175 return d
176
177 def _registerNewAccount(self, jid_, password, email, host, port):
178 kwargs = {}
179 if email:
180 kwargs['email'] = email
181 if host:
182 kwargs['host'] = host
183 if port:
184 kwargs['port'] = port
185 return self.registerNewAccount(jid.JID(jid_), password, **kwargs)
186
187 def registerNewAccount(self, jid_, password, email=None, host=u"127.0.0.1", port=C.XMPP_C2S_PORT):
188 """register a new account on a XMPP server
189
190 @param jid_(jid.JID): request jid to register
191 @param password(unicode): password of the account
192 @param email(unicode): email of the account
193 @param host(unicode): host of the server to register to
194 @param port(int): port of the server to register to
195 """
196 authenticator = RegisteringAuthenticator(jid_, password, email)
197 registered_d = authenticator.registered
198 serverRegistrer = xmlstream.XmlStreamFactory(authenticator)
199 connector = reactor.connectTCP(host, port, serverRegistrer)
200 serverRegistrer.clientConnectionLost = lambda conn, reason: connector.disconnect()
201 return registered_d
202
203 def _changePassword(self, new_password, profile_key):
204 client = self.host.getClient(profile_key)
205 return self.changePassword(client, new_password)
206
207 def changePassword(self, client, new_password):
208 iq_elt = self.buildRegisterIQ(client.xmlstream, client.jid, new_password)
209 d = iq_elt.send(client.jid.host)
210 d.addCallback(lambda dummy: self.host.memory.setParam("Password", new_password, "Connection", profile_key=client.profile))
211 return d
212
213 def _unregister(self, to_jid_s, profile_key):
214 client = self.host.getClient(profile_key)
215 return self.unregister(client, jid.JID(to_jid_s))
216
217 def unregister(self, client, to_jid):
218 """remove registration from a server/service
219
220 BEWARE! if you remove registration from profile own server, this will
221 DELETE THE XMPP ACCOUNT WITHOUT WARNING
222 @param to_jid(jid.JID): jid of the service or server
223 """
224 iq_elt = client.IQ()
225 iq_elt['to'] = to_jid.full()
226 query_elt = iq_elt.addElement((NS_REG, u'query'))
227 query_elt.addElement(u'remove')
228 return iq_elt.send()