|
| 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 Attachment Discovery iframe-related 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 pprint |
| 23 | +import requests |
| 24 | + |
| 25 | +import google.oauth2.credentials |
| 26 | +import googleapiclient.discovery |
| 27 | + |
| 28 | + |
| 29 | +@app.route("/") |
| 30 | +@app.route("/index") |
| 31 | +def index(): |
| 32 | + """ |
| 33 | + Render the index page from the "index.html" template. This is meant to act |
| 34 | + as a facsimile of a company's home page. |
| 35 | + The Add-on Discovery URL should be set to the /addon-discovery route below. |
| 36 | + """ |
| 37 | + |
| 38 | + return flask.render_template( |
| 39 | + "index.html", |
| 40 | + message="You've reached the index page.\nClick the button below to create a " |
| 41 | + "new Classroom assignment.", |
| 42 | + ) |
| 43 | + |
| 44 | + |
| 45 | +@app.route("/addon-discovery") |
| 46 | +def classroom_addon(): |
| 47 | + """ |
| 48 | + Checks if a user is signed in. If so, renders the addon discovery page from |
| 49 | + the "addon-discovery.html" template. This is meant to be the landing page |
| 50 | + when opening the web app in the Classroom add-on iframe. |
| 51 | + Otherwise, renders the "authorization.html" template. |
| 52 | +
|
| 53 | + Several GET query parameters can be passed when loading in the Classroom |
| 54 | + iframe. This example handles three additional parameters: |
| 55 | + - itemId: The ID of the stream item the add-on is being loaded in. |
| 56 | + - itemType: The type of the stream item the add-on is being loaded in. |
| 57 | + - courseId: The ID of the course the add-on is being loaded in. |
| 58 | + - addOnToken: A unique token provided by Classroom. |
| 59 | +
|
| 60 | + The full list of query parameters is available at |
| 61 | + https://developers.google.com/classroom/add-ons/developer-guides/iframes#attachment_discovery_iframe |
| 62 | + """ |
| 63 | + |
| 64 | + # Retrieve the itemId, itemType, courseId, and addOnToken query parameters. |
| 65 | + if flask.request.args.get("itemId"): |
| 66 | + flask.session["itemId"] = flask.request.args.get("itemId") |
| 67 | + # itemType will be one of the following: "announcement", "assignment", "material". |
| 68 | + # Use this value to route the user to the correct flow or to show an error message |
| 69 | + # if your app only supports specific item types. |
| 70 | + if flask.request.args.get("itemType"): |
| 71 | + flask.session["itemType"] = flask.request.args.get("itemType") |
| 72 | + if flask.request.args.get("courseId"): |
| 73 | + flask.session["courseId"] = flask.request.args.get("courseId") |
| 74 | + if flask.request.args.get("addOnToken"): |
| 75 | + flask.session["addOnToken"] = flask.request.args.get("addOnToken") |
| 76 | + |
| 77 | + # If the login_hint query parameter is available, we'll store it in the session. |
| 78 | + if flask.request.args.get("login_hint"): |
| 79 | + flask.session["login_hint"] = flask.request.args.get("login_hint") |
| 80 | + |
| 81 | + # It's possible that we might return to this route later, in which case the |
| 82 | + # parameters will not be passed in. Instead, use the login_hint cached in the session. |
| 83 | + login_hint = flask.session.get("login_hint") |
| 84 | + |
| 85 | + # If there's still no login_hint query parameter, this must be their first time signing |
| 86 | + # in, so send the user to the sign in page. |
| 87 | + if login_hint is None: |
| 88 | + return ch.start_auth_flow("discovery_callback") |
| 89 | + |
| 90 | + # Check if we have any stored credentials for this user. |
| 91 | + credentials = ch._credential_handler.get_credentials(login_hint) |
| 92 | + |
| 93 | + # Redirect to the authorization page if we received login_hint but don't |
| 94 | + # have any stored credentials for this user. We need the refresh token |
| 95 | + # specifically. |
| 96 | + if credentials is None: |
| 97 | + return ch.start_auth_flow("discovery_callback") |
| 98 | + |
| 99 | + return flask.render_template( |
| 100 | + "addon-discovery.html", message="You've reached the addon discovery page." |
| 101 | + ) |
| 102 | + |
| 103 | + |
| 104 | +@app.route("/test/<request_type>") |
| 105 | +def test_api_request(request_type="username"): |
| 106 | + """ |
| 107 | + Tests an API request, rendering the result in the |
| 108 | + "show-api-query-result.html" template. |
| 109 | +
|
| 110 | + Args: |
| 111 | + request_type: The type of API request to test. Currently only "username" |
| 112 | + is supported. |
| 113 | + """ |
| 114 | + |
| 115 | + credentials = ch._credential_handler.get_credentials() |
| 116 | + if credentials is None: |
| 117 | + return ch.start_auth_flow("discovery_callback") |
| 118 | + |
| 119 | + # Create an API client and make an API request. |
| 120 | + fetched_data = "" |
| 121 | + |
| 122 | + if request_type == "username": |
| 123 | + user_info_service = googleapiclient.discovery.build( |
| 124 | + serviceName="oauth2", version="v2", credentials=credentials |
| 125 | + ) |
| 126 | + |
| 127 | + flask.session["username"] = user_info_service.userinfo().get().execute().get("name") |
| 128 | + |
| 129 | + fetched_data = flask.session.get("username") |
| 130 | + |
| 131 | + # Save credentials in case access token was refreshed. |
| 132 | + flask.session["credentials"] = ch._credential_handler.session_credentials_to_dict( |
| 133 | + credentials |
| 134 | + ) |
| 135 | + ch._credential_handler.save_credentials_to_storage(credentials) |
| 136 | + |
| 137 | + # Render the results of the API call. |
| 138 | + return flask.render_template( |
| 139 | + "show-api-query-result.html", |
| 140 | + data=json.dumps(fetched_data, indent=2), |
| 141 | + data_title=request_type, |
| 142 | + ) |
| 143 | + |
| 144 | + |
| 145 | +@app.route("/discovery-callback") |
| 146 | +def discovery_callback(): |
| 147 | + """ |
| 148 | + Runs upon return from the OAuth 2.0 authorization server. Fetches and stores |
| 149 | + the user's credentials, including the access token, refresh token, and |
| 150 | + allowed scopes. |
| 151 | + """ |
| 152 | + |
| 153 | + # Specify the state when creating the flow in the callback so that it can |
| 154 | + # verified in the authorization server response. |
| 155 | + flow = ch.build_flow_instance("discovery_callback", flask.session["state"]) |
| 156 | + |
| 157 | + # Use the authorization server's response to fetch the OAuth 2.0 tokens. |
| 158 | + authorization_response = flask.request.url |
| 159 | + flow.fetch_token(authorization_response=authorization_response) |
| 160 | + |
| 161 | + # Store credentials in the session. |
| 162 | + credentials = flow.credentials |
| 163 | + flask.session["credentials"] = ch._credential_handler.session_credentials_to_dict( |
| 164 | + credentials |
| 165 | + ) |
| 166 | + |
| 167 | + # The flow is complete! |
| 168 | + # Add the credentials to our persistent storage. |
| 169 | + # We'll extract the "id" value from the credentials to use as a key. |
| 170 | + # This is the user's unique Google ID, and will match the login_hint |
| 171 | + # query parameter in the future. |
| 172 | + |
| 173 | + # If we've reached this point, and there is already a record in our |
| 174 | + # database for this user, they must be obtaining new credentials; |
| 175 | + # update the stored credentials. |
| 176 | + ch._credential_handler.save_credentials_to_storage(credentials) |
| 177 | + |
| 178 | + return flask.render_template("close-me.html", redirect_destination="classroom_addon") |
| 179 | + |
| 180 | + |
| 181 | +@app.route("/revoke") |
| 182 | +def revoke(): |
| 183 | + """ |
| 184 | + Revokes the logged in user's credentials. |
| 185 | + """ |
| 186 | + |
| 187 | + if "credentials" not in flask.session: |
| 188 | + return flask.render_template( |
| 189 | + "addon-discovery.html", |
| 190 | + message="You need to authorize before " + "attempting to revoke credentials.", |
| 191 | + ) |
| 192 | + |
| 193 | + credentials = google.oauth2.credentials.Credentials(**flask.session["credentials"]) |
| 194 | + |
| 195 | + revoke = requests.post( |
| 196 | + "https://oauth2.googleapis.com/revoke", |
| 197 | + params={"token": credentials.token}, |
| 198 | + headers={"content-type": "application/x-www-form-urlencoded"}, |
| 199 | + ) |
| 200 | + |
| 201 | + ch._credential_handler.clear_credentials_in_session() |
| 202 | + |
| 203 | + status_code = getattr(revoke, "status_code") |
| 204 | + if status_code == 200: |
| 205 | + return ch.start_auth_flow("discovery_callback") |
| 206 | + else: |
| 207 | + return flask.render_template( |
| 208 | + "addon-discovery.html", message="An error occurred during revocation!" |
| 209 | + ) |
0 commit comments