Skip to content

Commit 4f27cd7

Browse files
authored
Usar service account para acceder a la planilla (#7)
1 parent af6e451 commit 4f27cd7

File tree

6 files changed

+212
-86
lines changed

6 files changed

+212
-86
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
*.swp
22
*.pyc
3+
/service_account.json

Pipfile

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ verify_ssl = true
44
name = "pypi"
55

66
[packages]
7-
gspread = "==0.2.*"
7+
requests = "==2.26.*"
8+
google-auth = "==1.34.*"
9+
gspread = "==4.0.*"
810
httplib2 = "==0.17.*"
911
oauth2client = "~=4.1"
1012
webargs = "~=5.0"

Pipfile.lock

Lines changed: 174 additions & 71 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

notas.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def get_sheet(worksheet_name):
2121
2222
Utiliza la constante global SPREADSHEET_KEY.
2323
"""
24-
client = gspread.authorize(notas_oauth.get_credenciales())
24+
client = gspread.authorize(notas_oauth.get_credenciales_spreadsheet())
2525
spreadsheet = client.open_by_key(SPREADSHEET_KEY)
2626
return spreadsheet.worksheet(worksheet_name)
2727

notas_oauth.py

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,30 +5,50 @@
55
import datetime
66
import httplib2
77
import os
8-
import sys
98

109
import oauth2client.client
10+
import google.oauth2.service_account
11+
import google.auth.transport.requests
1112

1213
_CLIENT_ID = os.environ["NOTAS_OAUTH_CLIENT"]
1314
_CLIENT_SECRET = os.environ["NOTAS_OAUTH_SECRET"]
1415
_OAUTH_REFRESH = os.environ["NOTAS_REFRESH_TOKEN"]
16+
_SERVICE_ACCOUNT_JSON = os.environ["NOTAS_SERVICE_ACCOUNT_JSON"]
1517

16-
_creds = oauth2client.client.OAuth2Credentials(
18+
SCOPES = ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/gmail.send"]
19+
20+
# TODO: Unificar autenticacion para planilla y cuenta de mail.
21+
# Por ahora no encontramos la forma de enviar mails usando la service account.
22+
# Mantenemos por un lado el service account para acceder a la planilla y el client id/secret para enviar mails.
23+
_creds_spreadhseet = google.oauth2.service_account.Credentials.from_service_account_file(_SERVICE_ACCOUNT_JSON, scopes=SCOPES)
24+
_creds_email = oauth2client.client.OAuth2Credentials(
1725
"", _CLIENT_ID, _CLIENT_SECRET, _OAUTH_REFRESH,
1826
datetime.datetime(2015, 1, 1),
1927
"https://accounts.google.com/o/oauth2/token", "notasweb/1.0")
2028

2129

22-
def get_credenciales():
23-
"""Devuelve nuestro objeto OAuth2Credentials, actualizado.
30+
def get_credenciales(creds, es_valida, refrescar):
31+
if not es_valida(creds):
32+
refrescar(creds)
33+
return creds
34+
2435

36+
def get_credenciales_spreadsheet():
37+
"""Devuelve nuestro objeto OAuth2Credentials para acceder a la planilla, actualizado.
2538
Esta función llama a _refresh() si el token expira en menos de 5 minutos.
2639
"""
27-
now = datetime.datetime.utcnow()
28-
valid_until = _creds.token_expiry - datetime.timedelta(minutes=5)
29-
30-
if valid_until < now:
31-
print("Generando nuevo token de acceso.", file=sys.stderr)
32-
_creds.refresh(httplib2.Http())
33-
34-
return _creds
40+
return get_credenciales(
41+
_creds_spreadhseet,
42+
lambda creds: creds.valid,
43+
lambda creds: creds.refresh(google.auth.transport.requests.Request())
44+
)
45+
46+
def get_credenciales_email():
47+
"""Devuelve nuestro objeto OAuth2Credentials para acceder al mail, actualizado.
48+
Esta función llama a _refresh() si el token expira en menos de 5 minutos.
49+
"""
50+
return get_credenciales(
51+
_creds_email,
52+
lambda creds: creds.token_expiry - datetime.timedelta(minutes=5) > datetime.datetime.utcnow(),
53+
lambda creds: creds.refresh(httplib2.Http())
54+
)

sendmail.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def sendmail(fromname, toaddr, link):
3232
msg["From"] = "{} <{}>".format(fromname, ACCOUNT)
3333
msg["To"] = toaddr
3434

35-
creds = notas_oauth.get_credenciales()
35+
creds = notas_oauth.get_credenciales_email()
3636
xoauth2_tok = "user={}\1" "auth=Bearer {}\1\1".format(
3737
ACCOUNT, creds.access_token).encode("utf-8")
3838
server = smtplib.SMTP('smtp.gmail.com', 587)

0 commit comments

Comments
 (0)