def google(request): """ 구글 소셜 로그인 시 사용 --- """ CLIENT_ID = '832271626552-bpmo24c8a7e1s2lfhs1jfl0ena583jt1.apps.googleusercontent.com' token = request.POST.get('id_token') try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]: # raise ValueError('Could not verify audience.') if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise ValueError('Wrong issuer.') # If auth request is from a G Suite domain: # if idinfo['hd'] != GSUITE_DOMAIN_NAME: # raise ValueError('Wrong hosted domain.') # ID token is valid. Get the user's Google Account ID from the decoded token. userid = idinfo['sub'] username = idinfo['email'] account = User.objects.filter(username=username) if account: serializer = UserSerializer(account[0]) return Response(serializer.data) nickname = idinfo['email'] email = idinfo['email'] pic_name = random.randrange(1, 13, 1) pic_name = f'accounts/pic_names/{pic_name}.jpg' user = User.objects.create_user(username, email=email, nickname=nickname, pic_name=pic_name, social=True, password=None) user.set_unusable_password() user.save() serializer = UserSerializer(user) return Response(serializer.data) except ValueError: # Invalid token return Response(status=status.HTTP_101_SWITCHING_PROTOCOLS)
def login(request): if request.data.get("google_id_token") is not None: auth_method = "google" google_id_token = request.data["google_id_token"] elif request.data.get("email") is not None and request.data.get("password") is not None: auth_method = "email" email = request.data.get("email") password = request.data.get("password") else: return Response(status=status.HTTP_400_BAD_REQUEST) try: full_name = "" profile_image_url = None if auth_method == "google": try: id_info = id_token.verify_oauth2_token( google_id_token, googlerequests.Request(), "3890518873-9igg3o5c5c45a3cnq3fku68jrvc5ricj.apps.googleusercontent.com") except ValueError as value_error: print(value_error) return Response(data=str(value_error), status=status.HTTP_401_UNAUTHORIZED) print(id_info) if id_info['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: return Response(status=status.HTTP_403_FORBIDDEN, data='Wrong issuer {}'.format(id_info['iss'])) if id_info.get('hd') != "deepen.ai" and id_info.get('hd') != "deepenai.com" \ and id_info["email"] != "*****@*****.**" \ and id_info["email"] != "*****@*****.**": return Response(status=status.HTTP_403_FORBIDDEN, data='Unauthorized user {}'.format(id_info)) user_id = id_info["sub"] email = id_info["email"] full_name = id_info["name"] profile_image_url = id_info["picture"] else: user = UserModel.objects(email=email, password=password) if len(user) == 0: return Response(status=status.HTTP_403_FORBIDDEN, data='Unauthorized user {}'.format(email)) user_id = user[0]["user_id"] email = user[0]["email"] return create_jwt_token(user_id, email, full_name=full_name, profile_image_url=profile_image_url) except: print "Unexpected error:", sys.exc_info() traceback.print_tb(sys.exc_info()[2]) return Response(data=str(sys.exc_info()), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def verify_creds(flow: google_auth_oauthlib.flow.Flow, google_info, settings: Settings) -> dict: creds = flow.credentials req = requests.Request() id_info = id_token.verify_oauth2_token(creds._id_token, req, google_info["web"]["client_id"]) if "hd" not in id_info or id_info["hd"] != settings.top_domain: raise HTTPException( status_code=403, detail= f"Not an authorized domain {id_info.get('hd', '')},{settings.top_domain}", ) return id_info
def check_bot_authenticity(token, audience): if not token: raise ValueError("Invalid token") if not audience: raise ValueError(f"Invalid audience") id_info = id_token.verify_token( token, requests.Request(), audience=audience, certs_url=PUBLIC_CERT_URL_PREFIX + CHAT_ISSUER, ) if id_info["iss"] != CHAT_ISSUER: raise ValueError("Wrong issuer")
def sign_in(): body = json.loads(request.data) id_token = body.get('id_token') try: id_info = id_token.verify_oauth2_token(id_token, requests.Request(), client_id) username = id_info['sub'] user = users_dao.create_user(username) data = json.dumps({ "session_token": user.session_token, "session_expiration": str(user.session_expiration), "update_token": user.update_token }) return success_response(data, 201) except Exception: return failure_response("User invalid")
def read_jwt_token(req): """Extract the information from a JWT token.""" if os.getenv('FLASK_ENV', '') == 'development': return {'sub': '1234'} if not settings: initialize() app.logger.info('Checking auth for "%s"' % req.headers['Authorization']) jwt = req.headers['Authorization'].split(' ').pop() auth_request = requests.Request() app.logger.info('Checking JWT "%s"' % jwt) id_info = id_token.verify_oauth2_token(jwt, auth_request, settings['client_id']) if id_info['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise AssertionError( 'Got a token for the wrong issuer! (%s)' % id_info['iss']) return id_info
def oauthroute(): token = oauth.fetch_token('https://accounts.google.com/o/oauth2/token', authorization_response=request.url, client_secret=client_secret) req = requests.Request() id_info = id_token.verify_oauth2_token(token['id_token'], req, client_id) entity = datastore.entity.Entity( key=client.key(constants.users, id_info['sub'])) entity.update({"Email": id_info["email"]}) client.put(entity) print(id_info) return "Your JWT is: %s <br> <br> <br> Your unique ID is: %s" % ( token['id_token'], id_info['sub'])
def verify_token(token): try: id_info = id_token.verify_oauth2_token(token, requests.Request(), os.environ.get('CLIENT_ID')) if id_info['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise ValueError('Non-Google wrong issuer.') # ID token is valid. return id_info except ValueError: # Invalid token pass
def _generate_url(self, package): """ Generate a signed url to the GCS file """ blob = self._get_gcs_blob(package) if self.use_iam_signer: # Workaround for https://github.com/googleapis/google-auth-library-python/issues/50 signing_credentials = compute_engine.IDTokenCredentials( requests.Request(), "" ) else: signing_credentials = None return blob.generate_signed_url( expiration=timedelta(seconds=self.expire_after), credentials=signing_credentials, version="v4", )
def validate_token(token): """validates a token received from the client against Google's servers. on success, returns the EXTERNAL user id. on failure, returns None.""" try: idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) except ValueError as e: print(e) return None if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: return None return idinfo
def getUserDetails(data): data = request.get_json() CLIENT_ID = '471977914473-cn7u1rs5sopnfdh3a3u6bt17ecpp50t3.apps.googleusercontent.com' tokenResponse = id_token.verify_oauth2_token(data['token'], requests.Request(), CLIENT_ID) userDetails = { "name": tokenResponse['name'], "email": tokenResponse['email'], "user_uuid": tokenResponse['sub'], "email_verified": tokenResponse['email_verified'] } response = googleUserDetails(userDetails) return response
def verify_auth(id_token): error_message = None claims = None firebase_request_adapter = requests.Request() if id_token: try: claims = google.oauth2.id_token.verify_firebase_token( id_token, firebase_request_adapter) if 'email' not in claims: return {}, "USER EMAIL NOT FOUND" if 'name' not in claims: claims['name'] = claims['email'].split('@')[0] except ValueError as exc: error_message = str(exc) return claims, error_message
def auth(): token = request.json['id_token'] try: id_info = id_token.verify_oauth2_token(token, requests.Request(), GOOGLE_OAUTH2_CLIENT_ID) if id_info['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise ValueError('Wrong issuer.') except ValueError: # Invalid token raise ValueError('Invalid token') access_token = create_access_token(token) refresh_token = create_refresh_token(token) return jsonify({'access_token': access_token}), 200
def wrapper(*args, **kwargs): try: token = request.headers.get('Authorization') if not token: return {"error": "not authenticated"}, 401 token = token.replace('Bearer ', '') t = id_token.verify_oauth2_token( token, requests.Request(), ) except ValueError: return {"error": "not authenticated"}, 401 return func(*args, **kwargs)
def get_delegated_credentials(credentials, subject, scopes): try: request = requests.Request() credentials.refresh(request) signer = iam.Signer(request, credentials, config.GMAIL_SERVICE_ACCOUNT) creds = service_account.Credentials( signer=signer, service_account_email=config.GMAIL_SERVICE_ACCOUNT, token_uri=TOKEN_URI, scopes=scopes, subject=subject) except Exception: raise return creds
def credential(self): if not self._cred: client_info = self._client_info['installed'] token_uri = client_info['token_uri'] client_id = client_info['client_id'] client_secret = client_info['client_secret'] cred = credentials.Credentials(None, refresh_token=self._refresh_token, token_uri=token_uri, client_id=client_id, client_secret=client_secret) cred.refresh(g_requests.Request()) self._cred = cred elif not self._cred.valid: self.refresh() return self._cred
def veriauth_google(token): """ Verifies the allegedly authenticated Google user by submitted token. If the authentication is truthful, the user's email address is returned. """ # Verify the oauth token with Google idinfo = id_token.verify_oauth2_token(token, requests.Request(), oauth.__GOOGLE_SECRET) # Ensure that the cerificate issuer is Google, to prevent forgery if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise InvalidISSError("Invalid ISS") # ID token is valid. Get the user's Google Account ID from the decoded # token return idinfo['email'], idinfo['name']
def post(self, request): """ Log a user in. It expects in the request body the token received from google auth service. """ token = json.loads(request.body.decode('utf-8')).get('token') if token is None: return HttpResponse('Token is not provided', status=400) try: id_info = id_token.verify_oauth2_token(token, requests.Request(), settings.GOOGLE_CLIENT_ID) except ValueError: return HttpResponse('Bad token', status=400) if id_info['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise ValueError('Wrong issuer.') login_or_create_administrator(request, id_info) return HttpResponse('/admin')
def google(token): from google.oauth2 import id_token from google.auth.transport import requests as grequests try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, grequests.Request()) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]: # raise ValueError('Could not verify audience.') return idinfo except ValueError: # Invalid token return False
def verify(headers): try: if "Authorization" not in headers: return -1 bearer = headers["Authorization"] space_index = bearer.index(" ") prior = bearer[:space_index] if prior != "Bearer": raise ValueError jwt = bearer[space_index + 1:] req = requests.Request() id_info = id_token.verify_oauth2_token( str(jwt), req, client_id) return id_info["sub"] except ValueError: return -1
def SetUp(self): self.creds = c_google_auth.UserCredWithReauth( token='token', refresh_token='refresh_token', id_token='id_token', token_uri='token_uri', client_id='client_id', client_secret='client_secret', scopes=['scope1', 'scope2'], quota_project_id='quota_project_id') self.http_request = mock.MagicMock(spec=requests.Request()) self.get_rapt_token_mock = self.StartObjectPatch( oauth2client_reauth, 'GetRaptToken') self.now = datetime.datetime(2020, 1, 1) self.StartObjectPatch(_helpers, 'utcnow').return_value = self.now self.expected_expiry = datetime.datetime(2020, 1, 1, 1)
def get_email(request): if getenv("ENV") == "dev": return DEV_EMAIL token = request.json["token"] # validate token id_info = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) if id_info["iss"] not in [ "accounts.google.com", "https://accounts.google.com" ]: raise ValueError("Wrong issuer.") return id_info["email"]
def download(self, blobKey, fileName="", download="", sig="", *args, **kwargs): """ Download a file. :param blobKey: The unique blob key of the file. :type blobKey: str :param fileName: Optional filename to provide in the header. :type fileName: str :param download: Set header to attachment retrival, set explictly to "1" if download is wanted. :type download: str """ global credentials, bucket if not sig: raise errors.PreconditionFailed() # First, validate the signature, otherwise we don't need to proceed any further if not utils.hmacVerify(blobKey.encode("ASCII"), sig): raise errors.Forbidden() # Split the blobKey into the individual fields it should contain dlPath, validUntil = urlsafe_b64decode(blobKey).decode("UTF-8").split( "\0") if validUntil != "0" and datetime.strptime( validUntil, "%Y%m%d%H%M") < datetime.now(): raise errors.Gone() # Create a signed url and redirect the user if isinstance(credentials, ServiceAccountCredentials ): # We run locally with an service-account.json blob = bucket.get_blob(dlPath) if not blob: raise errors.NotFound() signed_url = blob.generate_signed_url(datetime.now() + timedelta(seconds=60)) else: # We are inside the appengine auth_request = requests.Request() signed_blob_path = bucket.blob(dlPath) expires_at_ms = datetime.now() + timedelta(seconds=60) signing_credentials = compute_engine.IDTokenCredentials( auth_request, "", service_account_email=credentials.service_account_email) signed_url = signed_blob_path.generate_signed_url( expires_at_ms, credentials=signing_credentials, version="v4") raise errors.Redirect(signed_url)
def addDeleteLoadsFromBoats(boat_id, load_id): req = requests.Request() try: authorizationHeader = request.headers['authorization'] authorizationHeader = authorizationHeader[7:] id_info = id_token.verify_oauth2_token( authorizationHeader, req, client_id) boat_key = client.key(constants.boats, int(boat_id)) boat = client.get(key=boat_key) load_key = client.key(constants.loads, int(load_id)) load = client.get(key=load_key) if request.method == 'PUT': if boat and boat["owner"] == id_info.get('sub'): if 'loads' in boat.keys(): boat['loads'].append(load.key.id) else: boat['loads'] = [load.key.id] client.put(boat) load['carrier'] = [boat.id] client.put(load) return('',204) elif boat and boat["owner"] != id_info.get('sub'): return_message = {"Error" : "You cannot load cargo onto boats you do not own"} return(json.dumps(return_message), 403) else: return_message = {"Error" : "No boat with this boat_id exists"} return(json.dumps(return_message), 404) if request.method == 'DELETE': if boat and boat["owner"] == id_info.get('sub'): if 'loads' in boat.keys(): boat['loads'].remove(int(load_id)) client.put(boat) load['carrier'].remove(int(boat_id)) client.put(load) return('',204) elif boat and boat["owner"] != id_info.get('sub'): return_message = {"Error" : "You cannot load cargo onto boats you do not own"} return(json.dumps(return_message), 403) else: return_message = {"Error" : "No boat with this boat_id exists"} return(json.dumps(return_message), 404) except KeyError: return ("Missing JWT", 401) except ValueError: return("Invalid JWT", 401)
def _create_channel(self): # Make sure grpc was successfully imported assert available() if not self._secure: return grpc.insecure_channel(self._host) # Authenticate the host. # # You're allowed to override the root certs and server if necessary. For # example, if you're running your proxy on localhost, you'll need to set # GRPC_PROXY_TLS_ROOTS to the "roots.crt" file specifying the certificate # for the root CA that your localhost server has used to certify itself, and # the GRPC_PROXY_TLS_OVERRIDE to the name that your server is using to # identify itself. For example, the ROOTS env var might be # "/path/to/roots.crt" while the OVERRIDE env var might be "test_server," if # this is what's used by the server you're running. # # If you're connecting to a real server with real SSL, none of this should # be used. if not certifi: self._debug_info.append('CERTIFI IS NOT PRESENT;' + ' gRPC HTTPS CONNECTIONS MAY FAIL') root_certs = None roots = os.environ.get('LUCI_GRPC_PROXY_TLS_ROOTS') if roots: self._debug_info.append('Overridden root CA: %s' % roots) with open(roots) as f: root_certs = f.read() else: self._debug_info.append('Using default root CAs from certifi') overd = os.environ.get('LUCI_GRPC_PROXY_TLS_OVERRIDE') options = () if overd: options = (('grpc.ssl_target_name_override', overd), ) ssl_creds = grpc.ssl_channel_credentials(root_certificates=root_certs) # Authenticate the user. scopes = ('https://www.googleapis.com/auth/cloud-source-tools', ) self._debug_info.append('Scopes are: %r' % scopes) user_creds, _ = google_auth.default(scopes=scopes) # Create the channel. request = google_auth_transport_requests.Request() self._debug_info.append('Options are: %r' % options) return google_auth_transport_grpc.secure_authorized_channel( user_creds, request, self._host, ssl_creds, options=options)
def login(): """ Handles all the login cases. GET: Shows the view containing OAuth providers for logging in. POST: Creates a new login session, thereby signing in the user. DELETE: Deletes the login session, thereby signing out the user. :return: the appropriate template. """ if request.method == "GET": state = get_csrf_token() session['state'] = state return render_template('login/new.html', state=state) if request.method == "POST": if not valid_state(): return json.dumps({'success': False}), 401, { 'ContentType': 'application/json' } token = request.form['token'] client_id = \ json.loads(open('../secrets/app_secrets.json', 'r').read())['web'][ 'google']["client_id"] try: idinfo = id_token.verify_oauth2_token(token, requests.Request(), client_id) session['idinfo'] = idinfo if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise ValueError('Wrong issuer.') except ValueError: print("Raised error") session.pop('idinfo') return json.dumps({'success': False}), 401, { 'ContentType': 'application/json' } create_user() return json.dumps({'success': True}), 200, { 'ContentType': 'application/json' } elif request.method == "DELETE": session.pop("idinfo") return json.dumps({'success': True}), 200, { 'ContentType': 'application/json' }
def login(): print('---This is a test---') token = request.form['idtoken'] print(token) try: idinfo = id_token.verify_oauth2_token(token, requests.Request(), GOOGLE_CLIENT_ID) session['idinfo'] = idinfo # here I will try to populate the users database by logging in print('------Inside Login------') print(idinfo) db = mysql.connect(user=db_user, password=db_pass, host=db_host, database=db_name) cursor = db.cursor() # This is to make sure user does not exist in the data base possible_user = idinfo['email'] # query = (f"select * from Users where email is {idinfo['email']}") query = ("SELECT * from Users where email=%s") values = (possible_user, ) cursor.execute(query, values) response = cursor.fetchall() if len(response) == 0: try: cursor.execute( 'INSERT INTO Users(email, firstName, lastName, urlToProfilePic ) VALUES (%s,%s,%s,%s)', (idinfo['email'], idinfo['given_name'], idinfo['family_name'], idinfo['picture'])) db.commit() except Exception as e: print(e) print('there was an error') # Selecting Users to make sure data base works cursor.execute("select * from Users;") print('---------- DATABASE Users INITIALIZED ----------') [print(x) for x in cursor] db.close() return idinfo except ValueError: print('Invalid token') return 'invalid token'
def check_user(request): if request.method != "POST": raise Http404 token = request.POST.get("id_token", "#") try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token( token, requests.Request(), "596099888829-6vvcos64bnlgs0nrltala1id8g1k40hb.apps.googleusercontent.com" ) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]: # raise ValueError('Could not verify audience.') if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise ValueError('Wrong issuer.') # If auth request is from a G Suite domain: # if idinfo['hd'] != GSUITE_DOMAIN_NAME: # raise ValueError('Wrong hosted domain.') # ID token is valid. Get the user's Google Account ID from the decoded token. userid = idinfo['sub'] print("got the user id", userid, idinfo['email']) if is_logged(request): if request.session.get('email', '#') != idinfo['email']: log_out(request) request.session['email'] = idinfo['email'] if Users.objects.filter(email=idinfo['email']).count() < 1: usr = Users() usr.email = idinfo['email'] usr.gid = userid usr.save() error = "Okay" else: error = "Already Logged" else: request.session['email'] = idinfo['email'] error = "Okay" except ValueError: # Invalid token pass return HttpResponse(error)
def BAD_generate_download_signed_url_v4(name: str): """Generates a v4 signed URL for downloading a blob. Note that this method requires a service account key file. You can not use this if you are using Application Default Credentials from Google Compute Engine or from the Google Cloud SDK. """ # bucket_name = 'your-bucket-name' # blob_name = 'your-object-name' import os KEYFILE = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") PROJECT = 'curatedmetagenomics' print(KEYFILE) import google.auth from google.oauth2 import service_account from google.auth.transport import requests from google.auth import compute_engine credentials, project = google.auth.default() bucket_name='data-curatedmetagenomics' storage_client = storage.Client(project, credentials) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(name) auth_request = requests.Request() signing_credentials = compute_engine.IDTokenCredentials( auth_request, "", service_account_email=credentials.service_account_email) url = blob.generate_signed_url( credentials = signing_credentials, version="v4", # This URL is valid for 15 minutes expiration=datetime.timedelta(minutes=15), # Allow GET requests using this URL. method="GET", ) print("Generated GET signed URL:") print(url) print("You can use this URL with any user agent, for example:") print("curl '{}'".format(url)) return url
def authorize_token(token): try: decoded_token = id_token.verify_oauth2_token( token, requests_google.Request(), "195081855240-jjsqpn2t0oucb8ets7li98p8vodja8jd.apps.googleusercontent.com" ) print(decoded_token) if (decoded_token.get( 'aud' ) == "195081855240-jjsqpn2t0oucb8ets7li98p8vodja8jd.apps.googleusercontent.com" and decoded_token.get('iss') == "accounts.google.com"): print('epicsauce') return decoded_token else: return False except: return False