async def _sign_in_with_token(self, request): args = validate_required_params(request.args, 'idtoken') token = args['idtoken'][0].replace("'", "").replace('"', '') try: session = requests.session() cached_session = cachecontrol.CacheControl(session) request = google.auth.transport.requests.Request( session=cached_session) id_info = id_token.verify_oauth2_token(token, request, self.client_id) if id_info['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise ValueError('Wrong issuer.') user_id = id_info['sub'] user_nickname = id_info['name'] user_photo = str(id_info['picture']).replace('=s96-c', '') session_token = self._db_manager.sign_in_or_create_oauth_user( user_id, user_nickname, user_photo) response = json({'session_token', session_token}) response.cookies['session_token'] = session_token return response except ValueError: raise Unauthorized('Token not accepted') pass
async def post(self, request): args = validate_required_params(request.args, 'idtoken') token = args['idtoken'][0].replace("'", "").replace('"', '') # example from https://developers.google.com/identity/sign-in/web/backend-auth try: session = requests.session() cached_session = cachecontrol.CacheControl(session) request = google.auth.transport.requests.Request( session=cached_session) id_info = id_token.verify_oauth2_token(token, request, CLIENT_ID) if id_info['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise ValueError('Wrong issuer.') user_id = id_info['sub'] user_nickname = id_info['name'] user_photo = str(id_info['picture']).replace('=s96-c', '') session_token = self.db.sign_in_or_create_oauth_user( user_id, user_nickname, user_photo) response = json({'session_id': session_token}) response.cookies['session_token'] = session_token return response except ValueError: raise Unauthorized('Token not accepted') pass
def on_post(self, req, resp): if not validate_params(req.params, 'idtoken'): raise falcon.HTTPBadRequest( "oauth post requires 'idtoken' parameter") token = req.params['idtoken'].replace("'", "").replace('"', '') # example from https://developers.google.com/identity/sign-in/web/backend-auth try: session = requests.session() cached_session = cachecontrol.CacheControl(session) request = google.auth.transport.requests.Request( session=cached_session) id_info = id_token.verify_oauth2_token(token, request, CLIENT_ID) if id_info['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise ValueError('Wrong issuer.') user_id = id_info['sub'] user_nickname = id_info['name'] user_photo = str(id_info['picture']).replace('=s96-c', '') session_token = self.db.sign_in_or_create_oauth_user( user_id, user_nickname, user_photo) resp.status = falcon.HTTP_OK resp.body = session_token except ValueError: raise falcon.HTTPUnauthorized('Token not accepted') pass
def wrapper(*args, **kvargs): token = request.headers.get('idToken') session = requests.session() cached_session = cachecontrol.CacheControl(session) transport_request = google.auth.transport.requests.Request(session=cached_session) decoded_token = id_token.verify_oauth2_token(token, transport_request) if decoded_token['iss'] != 'accounts.google.com': raise AuthenticationFailedException() if email and decoded_token['email'] != email: raise AuthenticationFailedException() return f(*args, **kvargs)
def callback(): flow.fetch_token(authorization_response=request.url) if not session["state"] == request.args["state"]: abort(500) # State does not match! credentials = flow.credentials request_session = requests.session() cached_session = cachecontrol.CacheControl(request_session) token_request = google.auth.transport.requests.Request( session=cached_session) id_info = id_token.verify_oauth2_token(id_token=credentials._id_token, request=token_request, audience=GOOGLE_CLIENT_ID) session["google_id"] = id_info.get("sub") session["name"] = id_info.get("name") return redirect("/")
def __init__( self, project_id: Optional[Text] = None, hangouts_user_added_intent_name: Optional[Text] = "/user_added", hangouts_room_added_intent_name: Optional[Text] = "/room_added", hangouts_removed_intent_name: Optional[Text] = "/bot_removed", ) -> None: self.project_id = project_id self.hangouts_user_added_intent_name = hangouts_user_added_intent_name self.hangouts_room_added_intent_name = hangouts_room_added_intent_name self.hangouts_user_added_intent_name = hangouts_removed_intent_name # Google's Request obj (this is used to make HTTP requests) uses cached # session to fetch Google's service certs. Certs don't change frequently, # so it makes sense to cache request body, rather than getting it again # every message. Actual caching depends on response headers. # see: https://github.com/googleapis/google-auth-library-python/blob/main/google/oauth2/id_token.py#L15 # noqa: E501, W505 cached_session = cachecontrol.CacheControl(requests.session()) self.google_request = google.auth.transport.requests.Request( session=cached_session )
# from __future__ import absolute_import # import pickle import logging import cachecontrol import google.auth.transport.requests import google.oauth2.id_token import requests from data import db # See https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.id_token.html # firebase_request_adapter = requests.Request() session = requests.session() cached_session = cachecontrol.CacheControl(session) firebase_request_adapter = google.auth.transport.requests.Request( session=cached_session) def get_user_claims(id_token): # Verify Firebase auth. error_message = None claims = None if id_token: try: # Verify the token against the Firebase Auth API. This example # verifies the token on each page load. For improved performance, # some applications may wish to cache results in an encrypted
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import cachecontrol from flask import request, redirect import google.auth.transport.requests from google.oauth2 import id_token import requests _PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') _PUBSUB_VERIFICATION_TOKEN = os.getenv('PUBSUB_VERIFICATION_TOKEN') _REQUEST = google.auth.transport.requests.Request( session=cachecontrol.CacheControl(requests.session())) def add(app): # pylint: disable=unused-variable,inconsistent-return-statements @app.before_request def before_filter(): # Skip auth filter for instance management and in development environment. if (request.path.startswith('/_ah/') # Start/stop instance. or ':808' in request.host): # Ports 8080/8081 are used in dev env. return # Authenticate PubSub push messages. if request.path.startswith('/push/'): # Check if request came from a CRMint's push subscription.
class HangoutHandler(InputChannel, BaseHandler): """ Channel that uses Google Hangouts Chat API to communicate. """ hangouts_user_added_intent_name: Optional[Text] = "/user_added", hangouts_room_added_intent_name: Optional[Text] = "/room_added", hangouts_removed_intent_name: Optional[Text] = "/bot_removed", cached_session = cachecontrol.CacheControl(requests.session()) google_request = google.auth.transport.requests.Request( session=cached_session ) @staticmethod def _extract_sender(request_data: Dict) -> Text: if request_data["type"] == "MESSAGE": return request_data["message"]["sender"]["displayName"] return request_data["user"]["displayName"] # noinspection PyMethodMayBeStatic def _extract_message(self, request_data: Dict) -> Text: message = None if request_data["type"] == "MESSAGE": message = request_data["message"]["text"] elif request_data["type"] == "CARD_CLICKED": message = request_data["action"]["actionMethodName"] elif request_data["type"] == "ADDED_TO_SPACE": if self._extract_room(request_data) and self.hangouts_room_added_intent_name: message = self.hangouts_room_added_intent_name elif not self._extract_room(request_data) and self.hangouts_user_added_intent_name: message = self.hangouts_user_added_intent_name elif ( request_data["type"] == "REMOVED_FROM_SPACE" and self.hangouts_user_added_intent_name ): message = self.hangouts_user_added_intent_name else: message = "" return message @staticmethod def _extract_room(request_data: Dict) -> Union[Text, None]: if request_data["space"]["type"] == "ROOM": return request_data["space"]["displayName"] def _extract_input_channel(self) -> Text: return self.name() def _check_token(self, bot_token: Text, project_id: Text) -> None: # see https://developers.google.com/chat/how-tos/bots-develop#verifying_bot_authenticity # noqa: E501, W505 # and https://google-auth.readthedocs.io/en/latest/user-guide.html#identity-tokens # noqa: E501, W505 decoded_token = {} try: decoded_token = id_token.verify_token( bot_token, self.google_request, audience=project_id, certs_url=CERTS_URL, ) except ValueError: abort(401) if decoded_token["iss"] != "*****@*****.**": abort(401) async def get(self, bot: str, token: str): self.write(json_encode({"status": "ok"})) async def post(self, bot: str, token: str): super().authenticate_channel(token, bot, self.request) hangout = ChatDataProcessor.get_channel_config("hangouts", bot=bot, mask_characters=False) project_id = hangout['config']['project_id'] request_data = json_decode(self.request.body) if project_id: token = self.request.headers.get("Authorization").replace("Bearer ", "") self._check_token(token, project_id) sender_id = self._extract_sender(request_data) room_name = self._extract_room(request_data) text = self._extract_message(request_data) if text is None: return response.text("OK") input_channel = self._extract_input_channel() collector = HangoutsOutput() try: await AgentProcessor.get_agent(bot).handle_message(UserMessage( text, collector, sender_id, input_channel=input_channel, metadata={"room": room_name, "out_channel": collector.name()}, )) except CancelledError: logger.error( "Message handling timed out for " "user message '{}'.".format(text) ) except Exception as e: logger.exception( f"An exception occurred while handling user message: {e}, " f"text: {text}" ) self.write(json_encode(collector.messages)) return
import flask import google.auth.transport.requests import json import logging import requests from cachecontrol import CacheControl from google.cloud import datastore from google.oauth2.id_token import verify_oauth2_token from shared import process CLIENT_ID = '308261241949-7948flf1cudha1bjaf5fu00sklsebbkl.apps.googleusercontent.com' SESSION = CacheControl(requests.session()) logging.basicConfig(level=logging.INFO) app = flask.Flask(__name__) @app.route('/call', methods=['POST']) def call(): ''' Main API route. ''' message = flask.request.get_json(force=True) # Extract and verify the ID token username = None if '_token' in message: request = google.auth.transport.requests.Request(session=SESSION)
def __init__(self, clientId): session = requests.session() self.clientId = clientId cached_session = cachecontrol.CacheControl(session) self.cached_request = google.auth.transport.requests.Request( session=cached_session)
def __init__(self): session = requests.session() self.client_id = os.environ.get(CIRRO_AUTH_CLIENT_ID) cached_session = cachecontrol.CacheControl(session) self.cached_request = google.auth.transport.requests.Request( session=cached_session)
"cellData": ALL_BATCHES[k]["cellData"]["cellData"], "codename": ALL_BATCHES[k]["codename"] }) # App Version MIN_VERSION = "1.0" MIN_VERSION_INTS = tuple(int(x) for x in MIN_VERSION.split(".")) APP_UPDATE_URL = "https://play.google.com/store/apps/details?id=com.app.byom" # Auth GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID', 'dummy') GOOGLE_OLD_CLIENT_ID = os.getenv('GOOGLE_OLD_CLIENT_ID', 'old-dummy') VALID_CLIENTS = {GOOGLE_CLIENT_ID, GOOGLE_OLD_CLIENT_ID} CACHED_SESSION = CacheControl(requests.session()) TOK_INFO_KEYS = {'aud', 'iss', 'email', 'sub', 'iat', 'exp'} VALID_ISSUERS = {'accounts.google.com', 'https://accounts.google.com'} NEW_APP_USER_AGENT_FRAGMENT = 'BYOM Smart Testing' AUTH_TOKEN_VALIDITY = 90 * 24 * 60 * 60 # 90 days validity of auth token # Postgres related psycopg2.extras.register_default_jsonb(loads=orjson.loads, globally=True) PG_POOL = psycopg2.pool.SimpleConnectionPool(1, 4, user="******", password="******", host="127.0.0.1", port="5432", database="covid", application_name="byom")
import functools from http import HTTPStatus import cachecontrol import firebase_admin import google.auth.transport.requests import google.oauth2.id_token import requests from bson.objectid import ObjectId from google.auth import jwt from quart import g, abort, request # See the example at # https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.id_token.html#module-google.oauth2.id_token SESSION = requests.session() CACHED_SESSION = cachecontrol.CacheControl(SESSION) REQUEST = google.auth.transport.requests.Request(session=CACHED_SESSION) ROLES = frozenset(['user', 'admin', 'recsys']) def check_auth(role_or_func, request_obj=None): """ Decorate request handlers to check that the request is authenticated with a Firebase JWT token (currently the only authentication method supported). Takes an optional 'role' parameter which can be a string or list of strings of required roles to access the endpoint. By default all authenticated clients regardless of role have access.