Getting google credentials for Youtube Data API in Flask - flask

I want to report comments using markAsSpam to YouTube comments where its ID's were extracted beforehand. The code below works but only in the terminal.
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
flow = InstalledAppFlow.from_client_secrets_file('client_secret.json', ["https://www.googleapis.com/auth/youtube.force-ssl"])
credentials = flow.run_console()
youtube = build('youtube', 'v3', credentials=credentials)
request = youtube.comments().markAsSpam(id='some_id')
request.execute()
The flow.run_console() shows a link in the terminal where the user visits to copy a string, so it can be entered in the terminal where the process continues and the comment is finally marked as spam. How do I make this work in the browser?

There's a complete example from Google that I found:
https://developers.google.com/identity/protocols/oauth2/web-server#python_5
For disabling the OAuthlib's HTTPS verification when running locally, there are several options answered in this other SO post:
Testing flask-oauthlib locally without https

Related

redirect_uri Parameter error on WeChat SSO on redirection of authentication url

I am implementing WeChat SSO for my web application, I have developer account, created an application there, followed this article exactly. I am using React on front-end and flask on backend.
I am using this package for flask for WeChat-sso.
So in my weChat dashboard I have registered official website e.g (chess.com), but I have to use callback url in such way so I can test redirection on my dev server.
My dev front-end is on (localhost:8000/)
My backend server is running on (127.0.0.1:5050/)
I have tried saving different callback urls e.g (127.0.0.1:5050/api/users/wechat/callback), no matter what I save in callback url always receiving parameter error.
So my question is how do I actually achieve this functionality locally? Instead of parameter error I should be seeing QR code so that I can get code from which I can get access_token. Following code generates authentication url
from weixin import WXAPPAPI
from weixin.lib.wxcrypt import WXBizDataCrypt
from weixin.client import WeixinAPI
scope = ("snsapi_login",)
api = WeixinAPI(appid=WECHAT_APP_ID,
app_secret=WECHAT_APP_SECRET,
redirect_uri=WECHAT_REDIRECT_URI)
authorize_url = api.get_authorize_url(scope=scope)
The authentication url generated is as follows, redirect URI is properly encoded just like in the documentation.
https://open.weixin.qq.com/connect/qrconnect?appid=wx35c78a124e8f027b&redirect_uri=127.0.0.1%3A5050%2Fapi%2Fusers%2Fwechat%2Fcallback&response_type=code&scope=snsapi_base&state=689db1f29605481a492639e98c7b1f9f#wechat_redirect
Please look at the picture of error as well thanks

How to authenticate URL from Spotipy on Linux with no browser

I'm trying to run a python script that uses spotipy, which needs a url link to be opened to authenticate the login. unfortunately I'm running this on the google cloud shell, so I can't open the browser link. and for some reason when I open it in my browser, it just redirects to localhost and doesn't authenticate (localhost is the Redirect URI). how can I authenticate?
I've tried opening the link on my MacBook instead of the linux virtual machine but just got redirected to localhost and nothing happens. I've tried xdg-open, curl, but haven't gotten anywhere.
Edit: I tried this -
import spotipy
import spotipy.util as util
from config import CLIENT_ID, CLIENT_SECRET, PLAY_LIST, USER
import random
token = util.oauth2.SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
cache_token = token.get_access_token()
spotify = spotipy.Spotify(cache_token)
results1 = spotify.user_playlist_tracks(USER, PLAY_LIST, limit=100, offset=0)
But got the error that only valid bearer authentication is accepted, so apparently it's kind of working. I'm not sure how to make the bearer valid.
Edit 2:
Solved it with these posts:
How to auth in spotipy without open web browser?
Persistent issues with Spotify Web API redirect URI

“This browser or app may not be secure” error while attempting to login in to Gmail account using GeckoDriver Firefox through Selenium and Python

I want to login to my gmail account using selenium. I use python2.7 .
It doesn't have error, but the page said that I couldn't sign in to my account because some reason. you can see the screenshot below.
it is my code:
import time
import selenium
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
EXE_PATH = r'C:\Users\LENOVO\Downloads\geckodriver.exe'
driver = webdriver.Firefox(executable_path=EXE_PATH)
def login():
mail = 'myMail'
pw = 'myPassword'
driver.get('https://gmail.com')
email = driver.find_element_by_name('identifier')
email.send_keys(mail)
driver.find_element_by_id('identifierNext').click()
time.sleep(10)
password = driver.find_element_by_name('password')
password.send_keys(pw)
driver.find_element_by_id('passwordNext').click()
what have to I do? please help me, I just a noob and beginner. thanks master
First install undetected-chromedriver using pip. It's a library which bypass Chrome security and allow you to proceed further.
pip install undetected-chromedriver
Then instead of creating using chromedriver.exe like driver = webdriver.Chrome(r"chromedriver.exe"), use the Chrome() function from the library you just installed.
Full Code Example in Python:
import undetected_chromedriver.v2 as uc
from time import sleep
username = 'example#gmail.com'
password ='password'
driver = uc.Chrome()
driver.delete_all_cookies()
driver.get('https://accounts.google.com/ServiceLogin')
sleep(2)
driver.find_element_by_xpath('//input[#type="email"]').send_keys(username)
driver.find_element_by_xpath('//*[#id="identifierNext"]').click()
sleep(2)
driver.find_element_by_xpath('//input[#type="password"]').send_keys(password)
driver.find_element_by_xpath('//*[#id="passwordNext"]').click()
sleep(2)
driver.get('https://gmail.com')
sleep(2)
The way to go around Googles automation detection, is by using the undetected_chromedriver library.
You can install the package using pip install undetected-chromedriver.
Once your driver object is initiated you can simply use selenium to operate the driver afterwards.
# initiate the driver with undetetcted_chromedriver
import undetected_chromedriver.v2 as uc
driver = uc.Chrome()
# operate the driver as you would with selenium
driver.get('https://my-url.com')
# Example use of selenium imports to be used with the driver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
try:
driver.find_element(By.XPATH, '//*[#id="my-id"]').click()
except NoSuchElementException:
print("No Such Element Exception")
Note: the login of Google is a popup, so don't forget to swap window handles to the popup to login and then afterwards to switch back to the main window.
This Google Support page states that sign in via browsers that "Use automation testing frameworks" is being disabled for the following security reasons and Google advices to do "Sign in with Google" using browser-based OAuth 2.0 authentication service.
As some websites, like stackoverflow.com allow you to sign in to their services using "Sign in with Google" it must happen via Google OAuth 2.0 authentication. This implicates that doing so you are also indirectly signing in to your Google account and therefore you can use all the Google services.
So you can fully automatically sign in to your Google account, e.g. by using a Python script, by performing these actions in your code:
Open a new browser window that is controlled by selenium webdriver
In the same window load the StackOverflow login page (or any other site that uses "Sign in with Google")
Choose for "Log in with Google"
Provide your Google account credentials and login to StackOverflow
Load the Google mailbox by opening https://mail.google.com/ or https://www.gmail.com/
This way you land down in your Gmail mailbox without performing any manual actions.
Please remember to add some 5s delays between different actions as doing it too quickly or too frequently can be recognized by StackOverflow as malicious automated actions and you can get blocked and you will need to make the manual I'm not a robot verification
I haven't really solved this but there is a workaround. If just logging in is your sole purpose then this might not be useful for you but if you wanna perform further operations and logging in using google is getting in your way then:
You can manually login in your chrome browser.
Use your default chrome profile to launch chrome.
To find path to your chrome profile data you need to type chrome://version/ in your address bar .
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=<Path to your chrome profile>")
chrome_driver_path = "C:/Users/..."
driver = webdriver.Chrome(executable_path=chrome_driver_path, chrome_options=options)
This would skip your login steps
I can't login google with selenium or headless-chromium-php,
but we can login google with chrome first, and find the "Profile Path" in "chrome://version/", for example my profile path is "/home/diyism/.config/google-chrome/Profile 2", then I copy it into "/home/diyism/.config/google-chrome/selenium-profiles/default", and run headless-chromium-php:
$factory = new \HeadlessChromium\BrowserFactory('/opt/google/chrome/chrome');
$browser = $factory->createBrowser([
'headless' => false,
'keepAlive' => true,
'userDataDir'=>'/home/diyism/.config/google-chrome/selenium-profiles'
]);
$page = $browser->createPage();
$page->navigate('https://mail.google.com')->waitForNavigation();
$pageTitle = $page->evaluate('document.title')->getReturnValue();
sleep(20);
$page->screenshot()->saveToFile('gmail.inbox.list.png');
Now I can see my gmail inbox list in gmail.inbox.list.png.
To make the sign-in work, simply go to google, click "manage this account" for the account you want to log-in via selenium, go to the security tab, scroll down till you see "Enhanced Safe Browsing for your account", and turn it off.
Open browser which controlled by selenium
Open StackOverflow site manually(or another site which have authorization with google)
Perform authorization with google manually
Then when you run your code again with gmail authorization it should work fine.
That seems to be a known problem with automated logins.
If you want to pursue that, you need to enable less secure apps in your gmail account.
https://myaccount.google.com/lesssecureapps
This setting may not be available for:
Accounts with 2-Step Verification enabled: Such accounts require an application-specific password for less secure apps access.
G Suite users: This setting is hidden if your administrator has locked less secure app account access.
Try this solution it worked for me I can even log in my Gmail now with this solution. after setting up the user-agent attribute it worked like a miracle.
<webview src="https://mail.google.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>

Why service_info is empty when using Python OneDrive sdk

I'm doing my internship in a company has very high security settings, sometimes something in the network will be blocked without any notice. And I don't really have admin role for my computer. Right now I met a problem, and not sure whether it's my permission issue.
I'm trying to upload files in Python code to OneDrive for Business, it's the company account.
This is the tutorial I'm using, check that OneDrive for Business part.
Before uploading the item, I should pass the authentication.
I have tested my code line by line, it worked well,
import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer
from onedrivesdk.helpers.resource_discovery import ResourceDiscoveryRequest
redirect_uri = 'http://localhost:8080'
client_secret = '[my client secret]'
client_id='[my client id]'
resourceId = "https://api.office.com/discovery/"
auth_server_url='https://login.microsoftonline.com/common/oauth2/authorize'
auth_token_url='https://login.microsoftonline.com/common/oauth2/token'
http = onedrivesdk.HttpProvider()
auth = onedrivesdk.AuthProvider(http,
client_id,
auth_server_url=auth_server_url,
auth_token_url=auth_token_url)
auth_url = auth.get_auth_url(redirect_uri)
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
auth.authenticate(code, redirect_uri, client_secret, resource=resourceId)
service_info = ResourceDiscoveryRequest().get_service_info(auth.access_token)
until when I am trying to get the service_info, it's empty....
Do you know why it's empty?
Or how can i keep writing the code here so that I could upload files to OneDrive for business?
I get the feeling that this is happening because our SDK drops all services where the service_api_version is less than 2.0. Assuming that the service you are trying to access works with API 2.0, then you can use this workaround to get past your issue.

Google Admin API using Oauth2 for a Service Account (Education Edition) - 403 Error

I'm having difficulties using Google new Admin SDK. In particular the Directory API using Oauth2.
I think I'm almost there but I've got stuck trying to retrieve a users details using the Directory API (I'm using a Google Education Edition domain).
Basically what I'm trying to do is write a python script that provisions or de-provisions users based on their enrollment status which is managed by our AD. I've got a script that does this using Oauth1 but want to update it to use Oauth2.
Here is a code snippet based on some examples I found.
f = file('test_key.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
'606346240424-10stfco1ukj9h4m4b4r40#developer.gserviceaccount.com',
key,
scope= 'https://www.googleapis.com/auth/admin.directory.user')
http = httplib2.Http()
http = credentials.authorize(http)
service = build(serviceName='admin', version='directory_v1', http=http)
lists = service.users().get(userKey='joe.blogs#mydomain.com').execute(http=http)
pprint.pprint(lists)
This piece of code appears to connect correctly but when I try to execute the query I get a 403 error.
ERROR: https://www.googleapis.com/admin/directory/v1/users/joe.blogs#mydomain.com?alt=json returned "Not Authorized to access this resource/api">
My first thought was because I haven't turned on this API on the administrators console (Google API's console) but I have. (Actually I turned on the Admin SDK and not the Directory API because there is no Directory API to turn on and seeing that it's part of the Admin SDK it would work?).
Is there another step I'm missing or have I made a silly mistake somewhere?
Bruce,
you're pretty close.
Couple of items:
If you're using App Engine, need to convert p12 key to pem and strip header
Need to include user with super user credentials (who has permission to do these operations) whom you're impersonating (not the user who is being changed) using the sub= parameter
So full code will look a bit like this:
# domain configuration settings
import domainconfig
f = file(domainconfig.KEY_FILE, "rb") # b reads file in binary mode; not strictly necessary, but safer to avoid strange Windows EOL characters: https://stackoverflow.com/questions/9644110/difference-between-parsing-a-text-file-in-r-and-rb-mode
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
domainconfig.SERVICE_ACCOUNT_EMAIL,
key,
scope = domainconfig.SCOPE,
sub=domainconfig.SUB_ACCOUNT_EMAIL # 'sub' supercedes the deprecated 'prn'
)
http = httplib2.Http()
http = credentials.authorize(http)
directoryservice = build("admin", "directory_v1", http=http)
users = directoryservice.users()
response = users.get(userKey='joe.blogs#mydomain.com').execute()
This should be of help: https://developers.google.com/drive/delegation
When asserting the credentials you need to connect it to the user that is going to be changed. From the link above, note this section:
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
scope='https://www.googleapis.com/auth/drive', sub=user_email)