1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.com>).
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
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
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.
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/>.
20 ##############################################################################
28 import werkzeug.exceptions
30 from openerp.modules.registry import RegistryManager
32 import openerp.addons.web.common.http as openerpweb
34 import web.common.http as openerpweb
36 from openid import oidutil
37 from openid.store import memstore
38 #from openid.store import filestore
39 from openid.consumer import consumer
40 from openid.cryptutil import randomString
41 from openid.extensions import ax, sreg
47 _logger = logging.getLogger('web.auth_openid')
48 oidutil.log = logging.getLogger('openid').debug
51 class GoogleAppsAwareConsumer(consumer.GenericConsumer):
52 def complete(self, message, endpoint, return_to):
53 if message.getOpenIDNamespace() == consumer.OPENID2_NS:
54 server_url = message.getArg(consumer.OPENID2_NS, 'op_endpoint', consumer.no_default)
55 if server_url.startswith('https://www.google.com/a/'):
57 for attr in ['claimed_id', 'identity']:
58 value = message.getArg(consumer.OPENID2_NS, attr)
59 value = 'https://www.google.com/accounts/o8/user-xrds?uri=%s' % urllib.quote_plus(value)
60 message.setArg(consumer.OPENID2_NS, attr, value)
62 # now, resign the message
63 assoc_handle = message.getArg(consumer.OPENID_NS, 'assoc_handle')
64 assoc = self.store.getAssociation(server_url, assoc_handle)
65 message.delArg(consumer.OPENID2_NS, 'sig')
66 message.delArg(consumer.OPENID2_NS, 'signed')
67 message = assoc.signMessage(message)
69 return super(GoogleAppsAwareConsumer, self).complete(message, endpoint, return_to)
72 class OpenIDController(openerpweb.Controller):
73 _cp_path = '/auth_openid/login'
75 _store = memstore.MemoryStore() # TODO use a filestore
77 _REQUIRED_ATTRIBUTES = ['email']
78 _OPTIONAL_ATTRIBUTES = 'nickname fullname postcode country language timezone'.split()
81 def _add_extensions(self, request):
82 """Add extensions to the request"""
84 sreg_request = sreg.SRegRequest(required=self._REQUIRED_ATTRIBUTES,
85 optional=self._OPTIONAL_ATTRIBUTES)
86 request.addExtension(sreg_request)
88 ax_request = ax.FetchRequest()
89 for alias in self._REQUIRED_ATTRIBUTES:
90 uri = utils.SREG2AX[alias]
91 ax_request.add(ax.AttrInfo(uri, required=True, alias=alias))
92 for alias in self._OPTIONAL_ATTRIBUTES:
93 uri = utils.SREG2AX[alias]
94 ax_request.add(ax.AttrInfo(uri, required=False, alias=alias))
96 request.addExtension(ax_request)
98 def _get_attributes_from_success_response(self, success_response):
101 all_attrs = self._REQUIRED_ATTRIBUTES + self._OPTIONAL_ATTRIBUTES
103 sreg_resp = sreg.SRegResponse.fromSuccessResponse(success_response)
105 for attr in all_attrs:
106 value = sreg_resp.get(attr)
107 if value is not None:
110 ax_resp = ax.FetchResponse.fromSuccessResponse(success_response)
112 for attr in all_attrs:
113 value = ax_resp.getSingle(utils.SREG2AX[attr])
114 if value is not None:
118 def _get_realm(self, req):
119 return req.httprequest.host_url
121 @openerpweb.jsonrequest
122 def verify(self, req, db, url):
123 redirect_to = werkzeug.urls.Href(req.httprequest.host_url + 'auth_openid/login/process')(session_id=req.session_id)
124 realm = self._get_realm(req)
126 session = dict(dbname=db, openid_url=url) # TODO add origin page ?
127 oidconsumer = consumer.Consumer(session, self._store)
130 request = oidconsumer.begin(url)
131 except consumer.DiscoveryFailure, exc:
132 fetch_error_string = 'Error in discovery: %s' % (str(exc[0]),)
133 return {'error': fetch_error_string, 'title': 'OpenID Error'}
136 return {'error': 'No OpenID services found', 'title': 'OpenID Error'}
138 req.session.openid_session = session
139 self._add_extensions(request)
141 if request.shouldSendRedirect():
142 redirect_url = request.redirectURL(realm, redirect_to)
143 return {'action': 'redirect', 'value': redirect_url, 'session_id': req.session_id}
145 form_html = request.htmlMarkup(realm, redirect_to)
146 return {'action': 'post', 'value': form_html, 'session_id': req.session_id}
149 @openerpweb.httprequest
150 def process(self, req, **kw):
151 session = getattr(req.session, 'openid_session', None)
153 return werkzeug.utils.redirect('/')
155 oidconsumer = consumer.Consumer(session, self._store, consumer_class=GoogleAppsAwareConsumer)
157 query = req.httprequest.args
158 info = oidconsumer.complete(query, req.httprequest.base_url)
159 display_identifier = info.getDisplayIdentifier()
161 session['status'] = info.status
164 if info.status == consumer.SUCCESS:
165 dbname = session['dbname']
166 with utils.cursor(dbname) as cr:
167 registry = RegistryManager.get(dbname)
168 Modules = registry.get('ir.module.module')
170 installed = Modules.search_count(cr, 1, ['&', ('name', '=', 'auth_openid'), ('state', '=', 'installed')]) == 1
173 Users = registry.get('res.users')
175 #openid_url = info.endpoint.canonicalID or display_identifier
176 openid_url = session['openid_url']
178 attrs = self._get_attributes_from_success_response(info)
179 attrs['openid_url'] = openid_url
180 session['attributes'] = attrs
181 openid_email = attrs.get('email', False)
185 domain += ['|', ('openid_email', '=', False)]
186 domain += [('openid_email', '=', openid_email)]
189 ('openid_url', '=', openid_url),
190 ('active', '=', True),
192 ids = Users.search(cr, 1, domain)
196 login = Users.browse(cr, 1, user_id).login
197 key = randomString(utils.KEY_LENGTH, '0123456789abcdef')
198 Users.write(cr, 1, [user_id], {'openid_key': key})
199 # TODO fill empty fields with the ones from sreg/ax
202 u = req.session.login(dbname, login, key)
205 session['message'] = 'This OpenID identifier is not associated to any active users'
208 elif info.status == consumer.SETUP_NEEDED:
209 session['message'] = info.setup_url
210 elif info.status == consumer.FAILURE and display_identifier:
211 fmt = "Verification of %s failed: %s"
212 session['message'] = fmt % (display_identifier, info.message)
214 # Either we don't understand the code or there is no
215 # openid_url included with the error. Give a generic
216 # failure message. The library should supply debug
217 # information in a log.
218 session['message'] = 'Verification failed.'
221 fragment = '#loginerror' if not user_id else ''
222 return werkzeug.utils.redirect('/'+fragment)
224 @openerpweb.jsonrequest
225 def status(self, req):
226 session = getattr(req.session, 'openid_session', {})
227 return {'status': session.get('status'), 'message': session.get('message')}
230 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: