-
Notifications
You must be signed in to change notification settings - Fork 0
/
app - copy.py
230 lines (188 loc) · 7 KB
/
app - copy.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
from __future__ import print_function
# Python standard libraries
import json
import os
import sqlite3
import flask
from flask_cors import CORS
# Third-party libraries
from flask import Flask, redirect, request, url_for
from flask_login import (
LoginManager,
current_user,
login_required,
login_user,
logout_user,
)
from oauthlib.oauth2 import WebApplicationClient
import requests
# Internal imports
# from db import init_db_command
from user import User
from googleapiclient.discovery import build
import google_auth_oauthlib.helpers
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import base64
# Configuration
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
GOOGLE_CLIENT_ID = "701150580333-9lqf3ot4ptha6k80j942km8l5pq5hd2s.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET = "CnWxlsvrnLi9Wbmdk2Txb6ES"
# GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", None)
# GOOGLE_CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET", None)
GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)
# Flask app setup
app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY") or os.urandom(24)
# User session management setup
# https://flask-login.readthedocs.io/en/latest
login_manager = LoginManager()
login_manager.init_app(app)
# Naive database setup
# try:
# init_db_command()
# except sqlite3.OperationalError:
# # Assume it's already been created
# pass
# OAuth 2 client setup
print(GOOGLE_CLIENT_ID)
print(GOOGLE_CLIENT_SECRET)
client = WebApplicationClient(GOOGLE_CLIENT_ID)
# Flask-Login helper to retrieve a user from our db
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
@app.route("/")
def index():
# return flask.jsonify(
# name="Roy Quitt",
# email="[email protected]",
# pic="https://lh3.googleusercontent.com/a-/AOh14GhoZiEKa6_e6IN1qiK9MUJWXRyFvQp-QUEIjl6BDA"
# )
if current_user.is_authenticated:
# return flask.jsonify(
# name=current_user.name,
# email=current_user.email,
# pic=current_user.profile_pic
# )
return (
"<p>Hello, {}! You're logged in! Email: {}</p>"
"<div><p>Google Profile Picture:</p>"
'<img src="{}" alt="Google profile pic"></img></div>'
'<div><a class="button" href="/getEvents">Get Events</a></div>'
'<div><p></p></div>'
'<a class="button" href="/logout">Logout</a>'.format(
current_user.name, current_user.email, current_user.profile_pic
)
)
else:
return '<a class="button" href="/login">Google Login</a>'
def get_google_provider_cfg():
return requests.get(GOOGLE_DISCOVERY_URL).json()
@app.route("/getEvents")
@login_required
def get_events():
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
url = 'https://www.googleapis.com/calendar/v3/calendars/primary/events?maxResults=5&timeMin=' + now
req = requests.Session()
print(client.token)
token = client.token.get("access_token")
print(token)
req = requests.get(url, headers={'Authorization': 'Bearer %s' % token}, data=None)
print("\nresponse:", req.text)
with open("sample.txt", "w", encoding="utf-8") as text_file:
text_file.write(req.text)
return redirect(url_for("index"))
@app.route("/login")
def login():
# Find out what URL to hit for Google login
google_provider_cfg = get_google_provider_cfg()
authorization_endpoint = google_provider_cfg["authorization_endpoint"]
# Use library to construct the request for Google login and provide
# scopes that let you retrieve user's profile from Google
request_uri = client.prepare_request_uri(
authorization_endpoint,
redirect_uri=request.base_url + "/callback",
scope=["openid", "email", "profile", 'https://www.googleapis.com/auth/calendar.readonly'],
)
return redirect(request_uri)
@app.route("/login/callback")
def callback():
# Get authorization code Google sent back to you
code = request.args.get("code")
# Find out what URL to hit to get tokens that allow you to ask for
# things on behalf of a user
google_provider_cfg = get_google_provider_cfg()
token_endpoint = google_provider_cfg["token_endpoint"]
# Prepare and send a request to get tokens! Yay tokens!
token_url, headers, body = client.prepare_token_request(
token_endpoint,
authorization_response=request.url,
redirect_url=request.base_url,
code=code
)
token_response = requests.post(
token_url,
headers=headers,
data=body,
auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
)
print("token type:", type(token_response))
# Parse the tokens!
print(token_response)
client.parse_request_body_response(json.dumps(token_response.json()))
# client.token
print(token_response)
# Now that you have tokens (yay) let's find and hit the URL
# from Google that gives you the user's profile information,
# including their Google profile image and email
userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
print("body:", body)
uri, headers, body = client.add_token(userinfo_endpoint)
print("headers:", headers, "\nbody:", body)
print("uri:", uri)
print("body:", body)
userinfo_response = requests.get(uri, headers=headers, data=body)
# url = 'https://www.googleapis.com/calendar/v3/users/me/calendarList'
# events_response = requests.post(url, headers={"authorization":})
# You want to make sure their email is verified.
# The user authenticated with Google, authorized your
# app, and now you've verified their email through Google!
print("test:\n")
print(type(userinfo_response))
print(userinfo_response.json())
if userinfo_response.json().get("email_verified"):
unique_id = userinfo_response.json()["sub"]
users_email = userinfo_response.json()["email"]
picture = userinfo_response.json()["picture"]
users_name = userinfo_response.json()["given_name"]
else:
return "User email not available or not verified by Google.", 400
# ------------- start Get Events -------------
# Create a user in your db with the information provided
# by Google
user = User(
id_=unique_id, name=users_name, email=users_email, profile_pic=picture
)
# Doesn't exist? Add it to the database.
if not User.get(unique_id):
User.create(unique_id, users_name, users_email, picture)
# Begin user session by logging the user in
login_user(user)
# Send user back to homepage
return redirect(url_for("index"))
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for("index"))
if __name__ == "__main__":
# app.run(host="10.50.1.146")
# app.run()
app.run(ssl_context="adhoc")