This repository has been archived by the owner on Jan 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
google_.py
592 lines (512 loc) · 23.1 KB
/
google_.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Raindrop.
#
# The Initial Developer of the Original Code is
# Mozilla Messaging, Inc..
# Portions created by the Initial Developer are Copyright (C) 2009
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
"""Google Responder
A Google responder that authenticates against Google using OpenID,
or optionally can use OpenId+OAuth hybrid protocol to request access to
Google Apps using OAuth2.
"""
import os
import urlparse
import socket
from openid.extensions import ax, pape
from openid.consumer import consumer
from openid import oidutil
import json
import logging
log = logging.getLogger(__name__)
from openid.consumer.discover import DiscoveryFailure
from openid.message import OPENID_NS, OPENID2_NS
import oauth2 as oauth
#from oauth2.clients.smtp import SMTP
import smtplib
import base64
from rfc822 import AddressList
import gdata.contacts
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header
from linkoauth.util import config, asbool, render
from linkoauth.util import safeHTML, literal
from linkoauth.oid_extensions import OAuthRequest
from linkoauth.oid_extensions import UIRequest
from linkoauth.openidconsumer import ax_attributes, attributes
from linkoauth.openidconsumer import OpenIDResponder
from linkoauth.oauth import get_oauth_config
from linkoauth.protocap import ProtocolCapturingBase, OAuth2Requestor
from linkoauth.errors import BackendError, OptionError, OAuthKeysException
GOOGLE_OAUTH = 'https://www.google.com/accounts/OAuthGetAccessToken'
domain = 'google.com'
class GoogleConsumer(consumer.GenericConsumer):
# a HACK to allow us to user google domains for federated login.
# this doesn't do the proper discovery and validation, but since we
# are forcing this to go through well known endpoints it is fine.
def _discoverAndVerify(self, claimed_id, to_match_endpoints):
oidutil.log('Performing discovery on %s' % (claimed_id,))
if not claimed_id.startswith('https://www.google.com/accounts/'):
# want to get a service endpoint for the domain, but keep the
# original claimed_id so tests during verify pass
g_claimed_id = \
"https://www.google.com/accounts/o8/user-xrds?uri=" + claimed_id
_, services = self._discover(g_claimed_id)
services[0].claimed_id = claimed_id
else:
_, services = self._discover(claimed_id)
if not services:
raise DiscoveryFailure('No OpenID information found at %s' %
(claimed_id,), None)
return self._verifyDiscoveredServices(claimed_id, services,
to_match_endpoints)
def complete(self, message, endpoint, return_to):
"""Process the OpenID message, using the specified endpoint
and return_to URL as context. This method will handle any
OpenID message that is sent to the return_to URL.
"""
mode = message.getArg(OPENID_NS, 'mode', '<No mode set>')
claimed_id = message.getArg(OPENID2_NS, 'claimed_id')
if not claimed_id.startswith('https://www.google.com/accounts/'):
# we want to be sure we have the correct endpoint with the
# google domain claimed_id hacked in
claimed_id = \
"https://www.google.com/accounts/o8/user-xrds?uri=" + claimed_id
_, services = self._discover(claimed_id)
endpoint = services[0]
modeMethod = getattr(self, '_complete_' + mode,
self._completeInvalid)
return modeMethod(message, endpoint, return_to)
class GoogleResponder(OpenIDResponder):
domain = 'google.com'
def __init__(self, consumer=None, oauth_key=None, oauth_secret=None,
request_attributes=None, domain='google.com',
*args, **kwargs):
"""Handle Google Auth
This also handles making an OAuth request during the OpenID
authentication.
"""
OpenIDResponder.__init__(self, domain)
self.consumer_key = str(self.config.get('consumer_key'))
self.consumer_secret = str(self.config.get('consumer_secret'))
# support for google apps domains
self.provider = domain
self.consumer_class = GoogleConsumer
@classmethod
def get_name(cls):
return cls.domain
def _lookup_identifier(self, identifier):
"""Return the Google OpenID directed endpoint"""
if identifier:
return \
"https://www.google.com/accounts/o8/site-xrds?hd=%s" % identifier
return "https://www.google.com/accounts/o8/id"
def _update_authrequest(self, authrequest, request):
"""Update the authrequest with Attribute Exchange and optionally OAuth
To optionally request OAuth, the request POST must include an
``oauth_scope``
parameter that indicates what Google Apps should have access requested.
"""
request_attributes = request.POST.get('ax_attributes',
ax_attributes.keys())
ax_request = ax.FetchRequest()
for attr in request_attributes:
ax_request.add(ax.AttrInfo(attributes[attr], required=True))
authrequest.addExtension(ax_request)
# Add PAPE request information.
# Setting max_auth_age to zero will force a login.
requested_policies = []
policy_prefix = 'policy_'
for k, v in request.POST.iteritems():
if k.startswith(policy_prefix):
policy_attr = k[len(policy_prefix):]
requested_policies.append(getattr(pape, policy_attr))
pape_request = pape.Request(requested_policies,
max_auth_age=request.POST.get('pape_max_auth_age', None))
authrequest.addExtension(pape_request)
oauth_request = OAuthRequest(consumer=self.consumer_key,
scope=self.scope or
'http://www.google.com/m8/feeds/')
authrequest.addExtension(oauth_request)
if 'popup_mode' in request.POST:
kw_args = {'mode': request.POST['popup_mode']}
if 'popup_icon' in request.POST:
kw_args['icon'] = request.POST['popup_icon']
ui_request = UIRequest(**kw_args)
authrequest.addExtension(ui_request)
return None
def _update_verify(self, consumer):
pass
def _get_access_token(self, request_token):
"""Retrieve the access token if OAuth hybrid was used"""
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
token = oauth.Token(key=request_token, secret='')
client = oauth.Client(consumer, token)
resp, content = client.request(GOOGLE_OAUTH, "POST")
if resp['status'] != '200':
return None
return dict(urlparse.parse_qsl(content))
def _get_credentials(self, result_data):
#{'profile': {'preferredUsername': u'mixedpuppy',
# 'displayName': u'Shane Caraveo',
# 'name':
# {'givenName': u'Shane',
# 'formatted': u'Shane Caraveo',
# 'familyName': u'Caraveo'},
# 'providerName': 'Google',
# 'verifiedEmail': u'mixedpuppy@gmail.com',
#'identifier':
#'https://www.google.com/accounts/o8/id?
# id=AItOawnEHbJcEY5EtwX7vf81_x2P4KUjha35VyQ'}}
# google OpenID for domains result is:
#{'profile': {
# 'displayName': u'Shane Caraveo',
# 'name': {'givenName': u'Shane',
# 'formatted': u'Shane Caraveo',
# 'familyName': u'Caraveo'},
# 'providerName': 'OpenID',
# 'identifier':
# u'http://g.caraveo.com/openid?id=103543354513986529024',
# 'emails': [u'mixedpuppy@g.caraveo.com']}}
profile = result_data['profile']
provider = domain
if profile.get('providerName').lower() == 'openid':
provider = 'googleapps.com'
userid = profile.get('verifiedEmail', '')
emails = profile.get('emails')
profile['emails'] = []
if userid:
profile['emails'] = [{'value': userid, 'primary': False}]
if emails:
# fix the emails list
for e in emails:
profile['emails'].append({'value': e, 'primary': False})
profile['emails'][0]['primary'] = True
account = {'domain': provider,
'userid': profile['emails'][0]['value'],
'username': profile.get('preferredUsername', '')}
profile['accounts'] = [account]
return result_data
# XXX right now, python-oauth2 does not raise the exception if there is an
# error, this is copied from oauth2.clients.smtp and fixed
class SMTP(smtplib.SMTP):
"""SMTP wrapper for smtplib.SMTP that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth.Token):
raise ValueError("Invalid token.")
xoauth_string = oauth.build_xoauth_string(url, consumer, token)
code, resp = self.docmd('AUTH',
'XOAUTH %s' % base64.b64encode(xoauth_string))
if code >= 500:
raise smtplib.SMTPResponseException(code, resp)
return code, resp
# A "protocol capturing" SMTP class - should move into its own module
# once we get support for other SMTP servers...
class SMTPRequestorImpl(SMTP, ProtocolCapturingBase):
pc_protocol = "smtp"
def __init__(self, host, port):
self._record = []
self.pc_host = host
SMTP.__init__(self, host, port)
ProtocolCapturingBase.__init__(self)
def pc_get_host(self):
return self.pc_host
def send(self, str):
msg = "> " + "\n+ ".join(str.splitlines()) + "\n"
self._record.append(msg)
SMTP.send(self, str)
def getreply(self):
try:
errcode, errmsg = SMTP.getreply(self)
except Exception, exc:
try:
module = getattr(exc, '__module__', None)
erepr = {'module': module, 'name': exc.__class__.__name__,
'args': exc.args}
self._record.append("E " + json.dumps(erepr))
except Exception:
log.exception("failed to serialize an SMTP exception")
raise
msg = "\n+ ".join(errmsg.splitlines()) + "\n"
self._record.append("< %d %s" % (errcode, msg))
return errcode, errmsg
def sendmail(self, *args, **kw):
SMTP.sendmail(self, *args, **kw)
if asbool(config.get('protocol_capture_success')):
self.save_capture("automatic success save")
def _save_capture(self, dirname):
with open(os.path.join(dirname, "smtp-trace"), "wb") as f:
f.writelines(self._record)
self._record = []
return None
SMTPRequestor = SMTPRequestorImpl
class GoogleRequester(object):
def __init__(self, account):
self.domain = domain
self.account = account
self.host = "smtp.gmail.com"
self.port = 587
self.config = get_oauth_config(domain)
try:
self.oauth_token = oauth.Token(
key=account.get('oauth_token'),
secret=account.get('oauth_token_secret'))
except ValueError, e:
# missing oauth tokens, raise our own exception
raise OAuthKeysException(str(e))
self.consumer_key = str(self.config.get('consumer_key'))
self.consumer_secret = str(self.config.get('consumer_secret'))
self.consumer = oauth.Consumer(key=self.consumer_key,
secret=self.consumer_secret)
@classmethod
def get_name(cls):
return domain
def sendmessage(self, message, options, headers):
if options is None:
options = {}
result = error = None
profile = self.account.get('profile', {})
from_email = from_ = profile['emails'][0]['value']
fullname = profile.get('displayName', None)
if fullname:
from_email = '"%s" <%s>' % (Header(fullname, 'utf-8').encode(),
Header(from_, 'utf-8').encode())
url = "https://mail.google.com/mail/b/%s/smtp/" % from_
# 'to' parsing
address_list = AddressList(options.get('to', ''))
if len(address_list) == 0:
return None, {
"provider": self.host,
"message": "recipient address must be specified",
"status": 0}
to_headers = []
for addr in address_list:
if not addr[1] or not '@' in addr[1]:
return None, {
"provider": self.host,
"message": "recipient address '%s' is invalid" % addr[1],
"status": 0}
if addr[0]:
to_ = '"%s" <%s>' % (Header(addr[0], 'utf-8').encode(),
Header(addr[1], 'utf-8').encode())
else:
to_ = Header(addr[1], 'utf-8').encode()
to_headers.append(to_)
if len(to_headers) == 0:
raise OptionError('the To header cannot be empty')
subject = options.get('subject', config.get('share_subject',
'A web link has been shared with you'))
title = options.get('title', options.get('link',
options.get('shorturl', '')))
description = options.get('description', '')[:280]
msg = MIMEMultipart('alternative')
msg.set_charset('utf-8')
msg.add_header('Subject', Header(subject, 'utf-8').encode())
msg.add_header('From', from_email)
for to_ in to_headers:
msg.add_header('To', to_)
extra_vars = {'safeHTML': safeHTML,
'options': options}
# insert the url if it is not already in the message
extra_vars['longurl'] = options.get('link')
extra_vars['shorturl'] = options.get('shorturl')
# reset to unwrapped for html email, they will be escaped
extra_vars['from_name'] = fullname
extra_vars['subject'] = subject
extra_vars['from_header'] = from_
extra_vars['title'] = title
extra_vars['description'] = description
extra_vars['message'] = message
extra_vars['thumbnail'] = options.get('picture_base64', "") != ""
mail = render('/html_email.mako', extra_vars=extra_vars)
mail = mail.encode('utf-8')
if extra_vars['thumbnail']:
part2 = MIMEMultipart('related')
html = MIMEText(mail, 'html')
html.set_charset('utf-8')
# FIXME: we decode the base64 data just so MIMEImage
# can re-encode it as base64
image = MIMEImage(base64.b64decode(options.get('picture_base64')),
'png')
image.add_header('Content-Id', '<thumbnail>')
image.add_header('Content-Disposition',
'inline; filename=thumbnail.png')
part2.attach(html)
part2.attach(image)
else:
part2 = MIMEText(mail, 'html')
part2.set_charset('utf-8')
# get the title, or the long url or the short url or nothing
# wrap these in literal for text email
extra_vars['from_name'] = literal(fullname)
extra_vars['subject'] = literal(subject)
extra_vars['from_header'] = literal(from_)
extra_vars['title'] = literal(title)
extra_vars['description'] = literal(description)
extra_vars['message'] = literal(message)
rendered = render('/text_email.mako', extra_vars=extra_vars)
part1 = MIMEText(rendered.encode('utf-8'), 'plain')
part1.set_charset('utf-8')
msg.attach(part1)
msg.attach(part2)
server = None
try:
server = SMTPRequestor(self.host, self.port)
# in the app:main set debug = true to enable
if asbool(config.get('debug', False)):
server.set_debuglevel(True)
try:
try:
server.starttls()
except smtplib.SMTPException:
log.info("smtp server does not support TLS")
try:
server.ehlo_or_helo_if_needed()
server.authenticate(url, self.consumer, self.oauth_token)
server.sendmail(from_, to_headers, msg.as_string())
except smtplib.SMTPRecipientsRefused, exc:
server.save_capture("rejected recipients")
for to_, err in exc.recipients.items():
error = {"provider": self.host,
"message": err[1],
"status": err[0]}
break
except smtplib.SMTPResponseException, exc:
server.save_capture("smtp response exception")
error = {"provider": self.host,
"message": "%s: %s" % (exc.smtp_code,
exc.smtp_error),
"status": exc.smtp_code}
except smtplib.SMTPException, exc:
server.save_capture("smtp exception")
error = {"provider": self.host,
"message": str(exc)}
except UnicodeEncodeError, exc:
server.save_capture("unicode error")
raise
except ValueError, exc:
server.save_capture("ValueError sending email")
error = {"provider": self.host,
"message": str(exc)}
except socket.timeout, exc:
server.save_capture('Timeout sending email')
error = {"provider": self.host,
"message": str(exc)}
raise BackendError(error)
finally:
try:
server.quit()
except smtplib.SMTPServerDisconnected:
# an error above may have already disconnected, so we can
# ignore the error while quiting.
pass
except smtplib.SMTPResponseException, exc:
if server is not None:
server.save_capture("early smtp response exception")
error = {"provider": self.host,
"message": "%s: %s" % (exc.smtp_code, exc.smtp_error),
"status": exc.smtp_code}
except smtplib.SMTPException, exc:
if server is not None:
server.save_capture("early smtp exception")
error = {"provider": self.host,
"message": str(exc)}
if error is None:
result = {"status": "message sent"}
return result, error
def getgroup_id(self, group, headers):
url = 'https://www.google.com/m8/feeds/groups/default/full?v=2'
method = 'GET'
client = oauth.Client(self.consumer, self.oauth_token)
resp, content = client.request(url, method, headers=headers)
feed = gdata.contacts.GroupsFeedFromString(content)
for entry in feed.entry:
this_group = entry.content.text
if this_group.startswith('System Group: '):
this_group = this_group[14:]
if group == this_group:
return entry.id.text
def getcontacts(self, options, headers):
start = int(options.get('start', 0))
page = int(options.get('page', 25))
group = options.get('group', None)
contacts = []
userdomain = 'default'
# google domains can have two contacts lists, the users and the domains
# shared contacts.
# shared contacts are only available in paid-for google domain accounts
# and do not show the users full contacts list. I also did not find
# docs on how to detect whether shared contacts is available or not,
# so we will bypass this and simply use the users contacts list.
#profile = self.account.get('profile', {})
#accounts = profile.get('accounts', [{}])
#if accounts[0].get('domain') == 'googleapps.com':
# # set the domain so we get the shared contacts
# userdomain = accounts[0].get('userid').split('@')[-1]
url = ('http://www.google.com/m8/feeds/contacts/%s/full?'
'v=1&orderby=lastmodified&sortorder=descending'
'&max-results=%d') % (userdomain, page)
method = 'GET'
if start > 0:
url = url + "&start-index=%d" % (start,)
if group:
gid = self.getgroup_id(group, headers)
if not gid:
error = {"provider": domain,
"message": "Group '%s' not available" % group}
return None, error
url = url + "&group=%s" % (gid,)
# itemsPerPage, startIndex, totalResults
requestor = OAuth2Requestor(self.consumer, self.oauth_token)
resp, content = requestor.request(url, method, headers=headers)
if int(resp.status) != 200:
requestor.save_capture("contact fetch failure")
error = {"provider": domain,
"message": content,
"status": int(resp.status)}
return None, error
feed = gdata.contacts.ContactsFeedFromString(content)
for entry in feed.entry:
#print entry.group_membership_info
if entry.email:
p = {'displayName': entry.title.text, 'emails': []}
for email in entry.email:
p['emails'].append({'value': email.address,
'primary': email.primary})
if not p['displayName']:
p['displayName'] = email.address
contacts.append(p)
result = {
'entry': contacts,
'itemsPerPage': feed.items_per_page.text,
'startIndex': feed.start_index.text,
'totalResults': feed.total_results.text,
}
# create our pageData object if necessary
next_start = int(feed.start_index.text) + int(feed.items_per_page.text)
if next_start < int(feed.total_results.text):
result['pageData'] = {
'start': next_start,
'page': page,
'group': group
}
return result, None