|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2021 Google LLC |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 5 | +# use this file except in compliance with the License. You may obtain a copy of |
| 6 | +# the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | +# License for the specific language governing permissions and limitations under |
| 14 | +# the License. |
| 15 | +"""Defines all routes for the Flask server.""" |
| 16 | + |
| 17 | +from webapp import app |
| 18 | +from webapp import credential_handler as ch |
| 19 | + |
| 20 | +import json |
| 21 | +import flask |
| 22 | +import requests |
| 23 | + |
| 24 | +import google.oauth2.credentials |
| 25 | +import googleapiclient.discovery |
| 26 | + |
| 27 | + |
| 28 | +@app.route("/") |
| 29 | +@app.route("/index") |
| 30 | +def index(): |
| 31 | + """ |
| 32 | + Render the index page from the "index.html" template. This is meant to act |
| 33 | + as a facsimile of a company's home page. |
| 34 | + The Add-on Discovery URL should be set to the /classroom-addon route below. |
| 35 | + """ |
| 36 | + |
| 37 | + return flask.render_template( |
| 38 | + "index.html", message="You've reached the index page.") |
| 39 | + |
| 40 | + |
| 41 | +@app.route("/classroom-addon") |
| 42 | +def classroom_addon(): |
| 43 | + """ |
| 44 | + Checks if a user is signed in. If so, renders the addon discovery page from |
| 45 | + the "addon-discovery.html" template. This is meant to be the landing page |
| 46 | + when opening the web app in the Classroom add-on iframe. |
| 47 | + Otherwise, renders the "authorization.html" template. |
| 48 | + """ |
| 49 | + |
| 50 | + # Retrieve the postId, courseId, and addOnToken query parameters. |
| 51 | + if flask.request.args.get("postId"): |
| 52 | + flask.session["postId"] = flask.request.args.get("postId") |
| 53 | + if flask.request.args.get("courseId"): |
| 54 | + flask.session["courseId"] = flask.request.args.get("courseId") |
| 55 | + if flask.request.args.get("addOnToken"): |
| 56 | + flask.session["addOnToken"] = flask.request.args.get("addOnToken") |
| 57 | + |
| 58 | + # Retrieve the login_hint and hd query parameters. |
| 59 | + login_hint = flask.request.args.get("login_hint") |
| 60 | + hd = flask.request.args.get("hd") |
| 61 | + |
| 62 | + # It's possible that we might return to this route later, in which case the |
| 63 | + # parameters will not be passed in. Instead, use the values cached in the session. |
| 64 | + |
| 65 | + # If neither query parameter is available, use the values in the session. |
| 66 | + if login_hint is None and hd is None: |
| 67 | + login_hint = flask.session.get("login_hint") |
| 68 | + hd = flask.session.get("hd") |
| 69 | + |
| 70 | + # If there's no login_hint query parameter, then check for hd. |
| 71 | + # Send the user to the sign in page. |
| 72 | + elif hd is not None: |
| 73 | + flask.session["hd"] = hd |
| 74 | + return ch.start_auth_flow("discovery_callback") |
| 75 | + |
| 76 | + # If the login_hint query parameter is available, we'll store it in the session. |
| 77 | + else: |
| 78 | + flask.session["login_hint"] = login_hint |
| 79 | + |
| 80 | + # Check if we have any stored credentials for this user. |
| 81 | + credentials = ch._credential_handler.get_credentials(login_hint) |
| 82 | + |
| 83 | + # Redirect to the authorization page if we received login_hint but don't |
| 84 | + # have any stored credentials for this user. We need the refresh token |
| 85 | + # specifically. |
| 86 | + if credentials is None: |
| 87 | + return ch.start_auth_flow("discovery_callback") |
| 88 | + |
| 89 | + return flask.render_template( |
| 90 | + "addon-discovery.html", |
| 91 | + message="You've reached the addon discovery page.") |
| 92 | + |
| 93 | + |
| 94 | +@app.route("/test/<request_type>") |
| 95 | +def test_api_request(request_type="username"): |
| 96 | + """ |
| 97 | + Tests an API request, rendering the result in the "show-api-query-result.html" template. |
| 98 | +
|
| 99 | + Args: |
| 100 | + request_type: The type of API request to test. Currently only "username" is supported. |
| 101 | + """ |
| 102 | + |
| 103 | + credentials = ch._credential_handler.get_credentials() |
| 104 | + if credentials is None: |
| 105 | + return ch.start_auth_flow("discovery_callback") |
| 106 | + |
| 107 | + # Create an API client and make an API request. |
| 108 | + fetched_data = "" |
| 109 | + |
| 110 | + if request_type == "username": |
| 111 | + user_info_service = googleapiclient.discovery.build( |
| 112 | + serviceName="oauth2", version="v2", credentials=credentials) |
| 113 | + |
| 114 | + flask.session["username"] = ( |
| 115 | + user_info_service.userinfo().get().execute().get("name")) |
| 116 | + |
| 117 | + fetched_data = flask.session.get("username") |
| 118 | + |
| 119 | + # Save credentials in case access token was refreshed. |
| 120 | + flask.session[ |
| 121 | + "credentials"] = ch._credential_handler.session_credentials_to_dict( |
| 122 | + credentials) |
| 123 | + ch._credential_handler.save_credentials_to_storage(credentials) |
| 124 | + |
| 125 | + # Render the results of the API call. |
| 126 | + return flask.render_template( |
| 127 | + "show-api-query-result.html", |
| 128 | + data=json.dumps(fetched_data, indent=2), |
| 129 | + data_title=request_type) |
| 130 | + |
| 131 | + |
| 132 | +@app.route("/discovery-callback") |
| 133 | +def discovery_callback(): |
| 134 | + """ |
| 135 | + Runs upon return from the OAuth 2.0 authorization server. Fetches and stores |
| 136 | + the user's credentials, including the access token, refresh token, and |
| 137 | + allowed scopes. |
| 138 | + """ |
| 139 | + |
| 140 | + # Specify the state when creating the flow in the callback so that it can |
| 141 | + # verified in the authorization server response. |
| 142 | + flow = ch.build_flow_instance("discovery_callback", flask.session["state"]) |
| 143 | + |
| 144 | + # Use the authorization server's response to fetch the OAuth 2.0 tokens. |
| 145 | + authorization_response = flask.request.url |
| 146 | + flow.fetch_token(authorization_response=authorization_response) |
| 147 | + |
| 148 | + # Store credentials in the session. |
| 149 | + credentials = flow.credentials |
| 150 | + flask.session[ |
| 151 | + "credentials"] = ch._credential_handler.session_credentials_to_dict( |
| 152 | + credentials) |
| 153 | + |
| 154 | + # The flow is complete! |
| 155 | + # Add the credentials to our persistent storage. |
| 156 | + # We'll extract the "id" value from the credentials to use as a key. |
| 157 | + # This is the user's unique Google ID, and will match the login_hint |
| 158 | + # query parameter in the future. |
| 159 | + |
| 160 | + # If we've reached this point, and there is already a record in our |
| 161 | + # database for this user, they must be obtaining new credentials; |
| 162 | + # update the stored credentials. |
| 163 | + ch._credential_handler.save_credentials_to_storage(credentials) |
| 164 | + |
| 165 | + return flask.render_template( |
| 166 | + "close-me.html", redirect_destination="classroom_addon") |
| 167 | + |
| 168 | + |
| 169 | +@app.route("/revoke") |
| 170 | +def revoke(): |
| 171 | + """ |
| 172 | + Revokes the logged in user's credentials. |
| 173 | + """ |
| 174 | + |
| 175 | + if "credentials" not in flask.session: |
| 176 | + return flask.render_template( |
| 177 | + "addon-discovery.html", |
| 178 | + message="You need to authorize before " + |
| 179 | + "attempting to revoke credentials.") |
| 180 | + |
| 181 | + credentials = google.oauth2.credentials.Credentials( |
| 182 | + **flask.session["credentials"]) |
| 183 | + |
| 184 | + revoke = requests.post( |
| 185 | + "https://oauth2.googleapis.com/revoke", |
| 186 | + params={"token": credentials.token}, |
| 187 | + headers={"content-type": "application/x-www-form-urlencoded"}) |
| 188 | + |
| 189 | + ch._credential_handler.clear_credentials_in_session() |
| 190 | + |
| 191 | + status_code = getattr(revoke, "status_code") |
| 192 | + if status_code == 200: |
| 193 | + return ch.start_auth_flow("discovery_callback") |
| 194 | + else: |
| 195 | + return flask.render_template( |
| 196 | + "addon-discovery.html", |
| 197 | + message="An error occurred during revocation!") |
0 commit comments