How to replace an existing video in Dailymotion API? - dailymotion-api

I'm building an app using Dailymotion API
https://developer.dailymotion.com/
with official python sdk
https://github.com/dailymotion/dailymotion-sdk-python
and writing video CRUD(Create, Read, Update, Delete) simply.
Create, Read, Delete were succeccfully completed, but encountering a weird response of the API about "Update".
Here is a simplified snippet of my code in my Django project,
def update(request, video_id):
user = request.user
video = get_object_or_404(Video, pk=video_id)
file_path = # define file_path from uploaded file object
input_title = # define input_title from post request
input_description = # define input_description from post request
d = get_dailymotion_d(user)
if d == 'revoked':
# do actions of logout and delete the user
try:
# get url for upload with the file_path on my server
url = d.upload(file_path)
# update
response = d.post('/video/' + video.dailymotion_video_id, {'url': url, 'title': input_title, 'description': input_description, 'published': 'true', 'channel': 'creation'})
# delete the video from my sever
video.file_field.delete()
return redirect('/videos')
except Exception as e:
print(e.args)
print('update failed..!')
# delete the video from my server
video.file_field.delete()
return redirect('/videos')
def get_dailymotion_d(user):
d = dailymotion.Dailymotion()
d.set_grant_type('token', api_key=settings.DAILYMOTION_API_KEY, api_secret=settings.DAILYMOTION_API_SECRET, scope=['email', 'userinfo', 'manage_videos'], info={'redirect_uri': settings.DAILYMOTION_REDIRECT_URI})
# get credentiaols from database
access_token = user.dailymotionuser.access_token
expires = user.dailymotionuser.expires
refresh_token = user.dailymotionuser.refresh_token
session_params = {'access_token': access_token, 'expires': expires, 'refresh_token': refresh_token}
# set the credentials
d._session_store.set(session_params)
# check if the user revoked or not
try:
force_refreshed_access_token = d.get_access_token(force_refresh=True)
except dailymotion.DailymotionAuthError as e:
print(e.args[0])
return 'revoked'
# get valid access token
valid_access_token = d.get_access_token()
# update database with the valid access token
DailymotionUser.objects.filter(user=user).update(access_token=valid_access_token, expires=expires, refresh_token=refresh_token)
# prepare dic of the valid access token
valid_access_token_dic = {'access_token': valid_access_token}
# set the valid access token
d._session_store.set(valid_access_token_dic)
return d
but the update fails except title field with the following message,
'access_forbidden: You are not allowed to change existing video source.'
from doc,
access_forbidden: Thrown when the user doesn't have the permission to access the data (e.g. missing a required scope to access certain fields).
but I'm sure that the permission has manage_videos scope which is an enough scope to update the existing video source because the doc says,
manage_videos: Allows to modify or delete the user's uploaded videos and to publish new ones.
and described above,
Only the title field of the video is updated with the input_title properly.
Thanks for reading, I researched their docs carefully, but still don't understand this response.

Only partner users can update the video source urls.
Best,

Related

How to implement google smart lock one tap sign in

I want to implement Google's One tap sign-up and automatic sign-in in my website with the help of documentation https://developers.google.com/identity/one-tap/web/ but I am getting confused on how to implement in python.
def smartlock(request):
try:
CLIENT_ID='*******'
csrf_token_cookie = self.request.cookies.get('g_csrf_token')
if not csrf_token_cookie:
webapp2.abort(400, 'No CSRF token in Cookie.')
csrf_token_body = self.request.get('g_csrf_token')
if not csrf_token_body:
webapp2.abort(400, 'No CSRF token in post body.')
if csrf_token_cookie != csrf_token_body:
webapp2.abort(400, 'Failed to verify double submit cookie.')
# Specify the CLIENT_ID of the app that accesses the backend:
idinfo = id_token.verify_oauth2_token(csrf_token_cookie, 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']
except ValueError:
# Invalid token
pass
'''
As mentioned in the 'Key Point' section of this page: The ID token is returned in the credential field, instead of the g_csrf_token field.
So, you need to get the idinfo with the code as below:
credential = self.request.get('credential')
idinfo = id_token.verify_oauth2_token(credential, requests.Request(), CLIENT_ID)
The g_csrf_token parameter is for different purpose. It makes sure the request was submitted from a page in your own domain, so as to prevent the cross-site-request-forge attacks.

Shopify API App Proxy with Rails verify Users

I am trying to configure an app proxy so users can submit a product for a Shopify store. I have seen multiple ways to so a signature and handle it so yet I am unable to get it working so the ShopifyAPI will work. The action is below, I noticed that:shopify_session filter only works for admin, not customers as well.
def submit_product
query_parameters = Rack::Utils.parse_query(request.query_string)
# Remove and save the "signature" entry
signature = query_parameters.delete("signature")
sorted_params = query_parameters.collect{ |k, v| "#{k}=#{Array(v).join(',')}" }.sort.join
calculated_signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha256'), ENV['SHOPIFY_SECRET'], sorted_params)
raise 'Invalid signature' if signature != calculated_signature
#store = Store.where(shopify_url: query_parameters['shop']).first
if #store.present?
#product = #store.products.new
#product.images.build
#product_types = ShopifyAPI::CustomCollection.find(#store.customizable_collection_id).products
end
end
Before you can connect to the ShopifyAPI you should first establish an API session. Otherwise the ShopifyAPI::CustomCollection.find method can't connect to Shopify. Steps 3 and 4 of the shopify_api README include the following example:
session = ShopifyAPI::Session.new("SHOP_NAME.myshopify.com", token)
ShopifyAPI::Base.activate_session(session)
product_types = ShopifyAPI::CustomCollection.find(id)
token is the permanent access token which you can request during the OAuth Authentication phase (the installation of the App into a shop).

Twitter 3-legged authorization in Ruby

I am trying my hand ruby on rails. Mostly I have written code in Sinatra. Anyway this question may not have to do anything with framework. And this question may sound a very novice question. I am playing with Twitter 1.1 APIs and OAuth first time.
I have created an app XYZ and registered it with Twitter. I got XYZ's consumer key i.e., CONSUMER_KEY and consumer secret i.e. CONSUMER_SECRET. I also got XYZ's own access token i.e ACCESS_TOKEN and access secret i.e. ACCESS_SECRET
XYZ application type: Read, Write and Access direct messages
XYZ callback URL: http://www.mysite.com/cback
And I have checked: Allow this application to be used to Sign in with Twitter
What I am trying to do is very simple:
1) Users come to my website and click a link Link your twitter account (not signin with twitter)
2) That opens twitter popup where user grants permission to XYZ to perform actions on his/her behalf
3) Once user permits and popup gets closed, XYZ app gets user's access token and secret and save in the database.
4) Then XYZ uses that user's token and secret to perform actions in future.
I may be moron that such work flow has been implemented on several thousands sites and Twitter API documentations explain this 3-legged authentication, still I am unable to figure it out.
I have read https://dev.twitter.com/docs/auth/3-legged-authorization and https://dev.twitter.com/docs/auth/implementing-sign-twitter Unfortunately no ruby code found on internet that explains with step by step example.
What link should be used to open twitter authentication page when user clicks Link your twitter account.
Can anyone here, write some pseudo code with my pseduo credential above to achieve my goal from beging till end of this work flow? Thanks.
UPDATE:
I started with requesting request token as
require 'oauth'
consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET,
{ site: "https://twitter.com"})
request_token = consumer.get_request_token oauth_callback: 'http://www.mysite.com/tauth'
redirect_to request_token.authorize_url
I'm not familiar with ROR but here is the workflow of the OAuth 'dance' that you need to follow when the user clicks your button:
Obtain an unauthorized request token from Twitter by sending a
request to
POST https://api.twitter.com/oauth/request_token
signing the request using your consumer secret. This will be done in the background and
will be transparent to the user.
You will receive am oauth_token and oauth_token_secret back from
twitter.
Redirect the user to
https://api.twitter.com/oauth/authorize?oauth_token=[token_received_from_twitter]
using the oauth token value you received from Twitter in step 2.
When the user authorizes your app they will be redirected to your
callback url with oauth_token and oauth_verifier appended to the
url. i.e.
http://www.mysite.com/cback?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&oauth_verifer=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY
Convert the request token into an access token by sending a signed
request along with the oauth_verifier to
POST
https://api.twitter.com/oauth/access_token
signing your request
with your consumer secret and the token secret received in step 2.
If everything goes ok, you will receive a new oauth_token and
oauth_token_secret from Twitter. This is your access token for the
user.
Using the access token and secret received in step 6 you can make
Twitter api calls on behalf the the user by sending signed requests
to the appropriate api endpoints.
Hope you solved your problem by this time, but I built this sample Sign in with Twitter ruby web app that provide all explanation you need to do this integration. Below there's a class that implements all necessary methods with comments:
require "net/https"
require "simple_oauth"
# This class implements the requests that should
# be done to Twitter to be able to authenticate
# users with Twitter credentials
class TwitterSignIn
class << self
def configure
#oauth = YAML.load_file(TWITTER)
end
# See https://dev.twitter.com/docs/auth/implementing-sign-twitter (Step 1)
def request_token
# The request to get request tokens should only
# use consumer key and consumer secret, no token
# is necessary
response = TwitterSignIn.request(
:post,
"https://api.twitter.com/oauth/request_token",
{},
#oauth
)
obj = {}
vars = response.body.split("&").each do |v|
obj[v.split("=").first] = v.split("=").last
end
# oauth_token and oauth_token_secret should
# be stored in a database and will be used
# to retrieve user access tokens in next requests
db = Daybreak::DB.new DATABASE
db.lock { db[obj["oauth_token"]] = obj }
db.close
return obj["oauth_token"]
end
# See https://dev.twitter.com/docs/auth/implementing-sign-twitter (Step 2)
def authenticate_url(query)
# The redirection need to be done with oauth_token
# obtained in request_token request
"https://api.twitter.com/oauth/authenticate?oauth_token=" + query
end
# See https://dev.twitter.com/docs/auth/implementing-sign-twitter (Step 3)
def access_token(oauth_token, oauth_verifier)
# To request access token, you need to retrieve
# oauth_token and oauth_token_secret stored in
# database
db = Daybreak::DB.new DATABASE
if dbtoken = db[oauth_token]
# now the oauth signature variables should be
# your app consumer keys and secrets and also
# token key and token secret obtained in request_token
oauth = #oauth.dup
oauth[:token] = oauth_token
oauth[:token_secret] = dbtoken["oauth_token_secret"]
# oauth_verifier got in callback must
# to be passed as body param
response = TwitterSignIn.request(
:post,
"https://api.twitter.com/oauth/access_token",
{:oauth_verifier => oauth_verifier},
oauth
)
obj = {}
vars = response.body.split("&").each do |v|
obj[v.split("=").first] = v.split("=").last
end
# now the we got the access tokens, store it safely
# in database, you're going to use it later to
# access Twitter API in behalf of logged user
dbtoken["access_token"] = obj["oauth_token"]
dbtoken["access_token_secret"] = obj["oauth_token_secret"]
db.lock { db[oauth_token] = dbtoken }
else
oauth_token = nil
end
db.close
return oauth_token
end
# This is a sample Twitter API request to
# make usage of user Access Token
# See https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials
def verify_credentials(oauth_token)
db = Daybreak::DB.new DATABASE
if dbtoken = db[oauth_token]
# see that now we use the app consumer variables
# plus user access token variables to sign the request
oauth = #oauth.dup
oauth[:token] = dbtoken["access_token"]
oauth[:token_secret] = dbtoken["access_token_secret"]
response = TwitterSignIn.request(
:get,
"https://api.twitter.com/1.1/account/verify_credentials.json",
{},
oauth
)
user = JSON.parse(response.body)
# Just saving user info to database
user.merge! dbtoken
db.lock { db[user["screen_name"]] = user }
result = user
else
result = nil
end
db.close
return result
end
# Generic request method used by methods above
def request(method, uri, params, oauth)
uri = URI.parse(uri.to_s)
# always use SSL, you are dealing with other users data
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
# uncomment line below for debug purposes
#http.set_debug_output($stdout)
req = (method == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri.request_uri)
req.body = params.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&")
req["Host"] = "api.twitter.com"
# Oauth magic is done by simple_oauth gem.
# This gem is enable you to use any HTTP lib
# you want to connect in OAuth enabled APIs.
# It only creates the Authorization header value for you
# and you can assign it wherever you want
# See https://github.com/laserlemon/simple_oauth
req["Authorization"] = SimpleOAuth::Header.new(method, uri.to_s, params, oauth)
http.request(req)
end
end
end
More detailed explanation at:
https://github.com/lfcipriani/sign_in_with_twitter_sample

Linkedin Oauth with Rails

We have been connecting to Linkedin for awhile now successfully. However, we get some errors from time to time and I'm hoping someone can help shed some light on this. Here's our code:
def linkedin_login
request_token = Linkedin.client.request_token(oauth_callback: "http://#{SITE_URL}/linkedin/auth/")
session[:linkedin_request_token] = request_token.token
session[:linkedin_request_secret] = request_token.secret
redirect_to request_token.authorize_url
end
def linkedin_auth
raise "Don't have proper session or oauth_verifier" if session[:linkedin_request_token].blank? or session[:linkedin_request_secret].blank? or params[:oauth_verifier].blank?
access_token = Linkedin.client.authorize_from_request(session[:linkedin_request_token], session[:linkedin_request_secret], params[:oauth_verifier])
raise "Nil access token" if access_token.blank?
redirect_to linkedin_process_path(token: access_token.first, secret: access_token.second)
end
We're hitting the "raise 'Don't have proper session or oauth_verifier'" more than I would expect. When looking at the ENV for the errors, those people don't have the session values set from the original method. We have before_filters set on the application controller so initialize the session, so I know it's active.
My next thought was whether "request_token" was generating a value request_token, and I've tried many times and they all bring something back. We get many of these a day. After the error, if the user tries again, it works fine, which is why I'm so confused.
any thoughts on what could cause this?
Based on your code, it looks like you're making the request token call every time the user logs into your application. That's not the proper method to authenticate. You really only need to fetch the request token once, then use that to upgrade for an access token (as you're doing in your linkedin_auth method). From there, just save the access token and secret in your DB and fetch it anytime you need to make an API call for that particular user.
Our authentication is described more in detail here: https://developer.linkedin.com/documents/authentication
Also, this is just a personal preference, but I like using the OAuth gem for Rails as opposed to using a LinkedIn wrapper. It's easy to use and light weight.
Just as an example, you could do your auth this way:
require 'oauth'
def auth
api_key = 'XXXXXXXXX'
api_secret = 'XXXXXXXXX'
configuration = { :site => 'https://api.linkedin.com',
:authorize_path => 'https://www.linkedin.com/uas/oauth/authenticate',
:request_token_path => 'https://api.linkedin.com/uas/oauth/requestToken',
:access_token_path => 'https://api.linkedin.com/uas/oauth/accessToken' }
consumer = OAuth::Consumer.new(api_key, api_secret, configuration)
#Request token
request_token = consumer.get_request_token
# Output request URL to console
puts "Please visit this URL: https://api.linkedin.com/uas/oauth/authenticate?oauth_token=" + request_token.token + " in your browser and then input the numerical code you are provided here: "
# Set verifier code
verifier = $stdin.gets.strip
# Retrieve access token object
#access_token = request_token.get_access_token(:oauth_verifier => verifier)
end
You would only need to invoke this method when the user first authorizes your app. Save their access token then use it for subsequent API calls. Note, my example makes use of the console to enter the PIN verifier. In a real world example you'd want to programmatically save the PIN in a session variable or in memory, then use it to get the access token.

How to authenticate to flickr with Flickraw gem

I want to upload a photo but need to authenticate with flickr in order to do so. I am using the flickraw gem but don't understand the instructions below:
require 'flickraw'
FlickRaw.api_key="... Your API key ..."
FlickRaw.shared_secret="... Your shared secret ..."
token = flickr.get_request_token(:perms => 'delete')
auth_url = token['oauth_authorize_url']
puts "Open this url in your process to complete the authication process : #{auth_url}"
puts "Copy here the number given when you complete the process."
verify = gets.strip
begin
flickr.get_access_token(token['oauth_token'], token['oauth_token_secret'], verify)
login = flickr.test.login
puts "You are now authenticated as #{login.username}"
rescue FlickRaw::FailedResponse => e
puts "Authentication failed : #{e.msg}"
end
Can someone explain to me what this code is doing and how I should use it.
First , you should open http service
rails server
On the Console , you will see
Open this url in your process to complete the authication process : http://xxxx.xxxx.xxxx.xxxx........
you have to copy the url and post it on your browser.
After log in , you will get a number , like
xxx-xxx-xxx
just copy it onto your console!
Create a new Flickr app. Get the api key and shared secret from there.
"flickr.get_request_token" creates a request oauth token from flickr. You might want to set permissions to :write if you want to upload instead of :delete
auth_url is where you have to redirect to. That url also contains the oauth request tokens that you just created.
Once you are in auth_url page ( for this you have to login to your Yahoo! account), you can authorize your app to access your flickr account. This gives a verification id.
Use that verification id to you can get the oauth access tokens using this method call 'flickr.get_access_token'
Once you have the Oauth access tokens, you could do any api queries on flickr that your :perms would allow.
The entire process is described in detail here - http://www.flickr.com/services/api/auth.oauth.html
I submitted a pull request but here is an updated form of the documentation that should make this more clear
== Simple
+#Place near the top of your controller i.e. underneath FlickrController < ApplicationController
require 'flickraw'
+#Create an initializer file i.e. Flickr.rb and place it in config -> initializers folder
FlickRaw.api_key="... Your API key ..."
FlickRaw.shared_secret="... Your shared secret ..."
+#Examples of how the methods work
list = flickr.photos.getRecent
id = list[0].id
...

Resources