Rails 5 Faraday connection for Facebook Omniauth - ruby

I have tried all the tricks in the book and all the possible solution in stack over flow.But still couldn't figure out the problem. The program pauses at the call back initiated stage and shows faraday connection : timed out. I have the following code:
gem 'omniauth', '~> 1.3', '>= 1.3.1'
gem 'omniauth-facebook'
Routes.rb
devise_for :users,
:path => '',
:path_names => {:sign_in => 'login', :sign_out => 'logout', :edit => 'profile' },
:controllers => {:omniauth_callbacks => 'omniauth_callbacks'}
/Controller.rb
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
sign_in_and_redirect #user, :event => :authentication
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"].except("extra")
redirect_to new_user_registration_url
end
end
end
/user.rb
class User < ApplicationRecord
def self.from_omniauth(auth)
user = User.where(email: auth.info.email).first
if user
return user
else
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.image = auth.info.image
user.password = Devise.friendly_token[0,20]
user.firstname = auth.info.first_name
user.lastname = auth.info.last_name
user.phonenumber == '0000000000'
user.tc == true
user.year == true
end
end
end
end
/devise.rb
config.omniauth:facebook,ENV['FACEBOOK_ID'],ENV['FACEBOOK_SECRET'],scope:'email',info_fields:'email,first_name,last_name'

Related

How to insert video youtube api v3 through service account with ruby

My goal is to let users of my app upload to my youtube account through my server.
I have a developer acount, with youtube data api enabled and a service account client setup and for some reason I am not authorized. I dug through the net to try and figure out why and found many things.
I tried giving permissions in the admin security settings with the projects client id and scope.
Many people were saying that this error is caused because I don't have a youtube account associated with my account. but I have no idea how to associate these.
This is my upload_video.rb script:
require 'rubygems'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/file_storage'
require 'google/api_client/auth/installed_app'
require 'certified'
DEVELOPER_KEY = "MY-DEVELOPER-KEY"
YOUTUBE_UPLOAD_SCOPE = 'https://www.googleapis.com/auth/youtube.upload'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
def get_authenticated_service
puts #PROGRAM_NAME
client = Google::APIClient.new(
:application_name => $PROGRAM_NAME,
:application_version => '1.0.0'
)
key = Google::APIClient::KeyUtils.load_from_pkcs12('oauth2service.p12', 'notasecret')
auth_client = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => YOUTUBE_UPLOAD_SCOPE,
:issuer => 'SERVICE ACCOUNT EMAIL ADDRESS',
:signing_key => key)
auth_client.fetch_access_token!
client.authorization = auth_client
youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)
return client, youtube
end
def upload2youtube file, title, description, category_id, keywords, privacy_status
client, youtube = get_authenticated_service
begin
body = {
:snippet => {
:title => title,
:description => description,
:tags => keywords.split(','),
:categoryId => category_id,
},
:status => {
:privacyStatus => privacy_status
}
}
videos_insert_response = client.execute!(
:api_method => youtube.videos.insert,
:body_object => body,
:media => Google::APIClient::UploadIO.new(file, 'video/*'),
:parameters => {
:uploadType => 'resumable',
:part => body.keys.join(',')
}
)
videos_insert_response.resumable_upload.send_all(client)
puts "Video id '#{videos_insert_response.data.id}' was successfully uploaded."
rescue Google::APIClient::TransmissionError => e
puts e.result.body
end
end
This is how I am running it from another script:
require 'google/api_client'
require_relative 'upload_video'
$PROGRAM_NAME = 'MY-PROJECT-NAME'
upload2youtube File.open("somevideo.avi"), "title", "description", 'categoryid', 'tag1,tag2,tag3', 'unlisted'
And this is the result:
{
"error": {
"errors": [
{
"domain": "youtube.header",
"reason": "youtubeSignupRequired",
"message": "Unauthorized",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Unauthorized"
}
}
What am I doing wrong
#!/usr/bin/ruby
require 'rubygems'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/file_storage'
require 'google/api_client/auth/installed_app'
require 'certified'
class Youtube_Helper
##client_email = '' #email id from service account (that really long email address...)
##youtube_email = '' #email associated with youtube account
##p12_file_path = '' #path to the file downloaded from the service account (Generate new p12 key button)
##p12_password = '' # password to the file usually 'notasecret'
##api_key = nil # The API key for non authenticated things like lists
YOUTUBE_UPLOAD_SCOPE = 'https://www.googleapis.com/auth/youtube.upload'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
##client = nil
##youtube = nil
FILE_POSTFIX = '-oauth2.json'
def initialize(client_email, youtube_email, p12_file_path, p12_password, api_key)
##client_email=client_email
##youtube_email=youtube_email
##p12_file_path=p12_file_path
##p12_password=p12_password
##api_key = api_key
end
def get_authenticated_service
credentialsFile = $0 + FILE_POSTFIX
needtoauthenticate = false
#api_client = Google::APIClient.new(
:application_name => $PROGRAM_NAME,
:application_version => '1.0.0'
)
key = Google::APIClient::KeyUtils.load_from_pkcs12(##p12_file_path, ##p12_password)
#auth_client = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => YOUTUBE_UPLOAD_SCOPE,
:issuer => ##client_email,
:person => ##youtube_email,
:signing_key => key)
if File.exist? credentialsFile
puts 'credential file exists'
puts credentialsFile.to_s
File.open(credentialsFile, 'r') do |file|
credentials = JSON.load(file)
if !credentials.nil?
puts 'get credentials from file'
#auth_client.access_token = credentials['access_token']
#auth_client.client_id = credentials['client_id']
#auth_client.client_secret = credentials['client_secret']
#auth_client.refresh_token = credentials['refresh_token']
#auth_client.expires_in = (Time.parse(credentials['token_expiry']) - Time.now).ceil
#api_client.authorization = #auth_client
if #auth_client.expired?
puts 'authorization expired'
needtoauthenticate = true
end
else
needtoauthenticate = true
end
end
else
needtoauthenticate = true
end
if needtoauthenticate
#auth_client.fetch_access_token!
#api_client.authorization = #auth_client
save(credentialsFile)
end
youtube = #api_client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)
##client = #api_client
##youtube = youtube
return #api_client, youtube
end
def save(credentialsFile)
File.open(credentialsFile, 'w', 0600) do |file|
json = JSON.dump({
:access_token => #auth_client.access_token,
:client_id => #auth_client.client_id,
:client_secret => #auth_client.client_secret,
:refresh_token => #auth_client.refresh_token,
:token_expiry => #auth_client.expires_at
})
file.write(json)
end
end
def upload2youtube file, title, description, category_id, keywords, privacy_status
puts 'begin'
begin
body = {
:snippet => {
:title => title,
:description => description,
:tags => keywords.split(','),
:categoryId => category_id,
},
:status => {
:privacyStatus => privacy_status
}
}
puts body.keys.join(',')
# Call the API's videos.insert method to create and upload the video.
videos_insert_response = ##client.execute!(
:api_method => ##youtube.videos.insert,
:body_object => body,
:media => Google::APIClient::UploadIO.new(file, 'video/*'),
:parameters => {
'uploadType' => 'multipart',
:part => body.keys.join(',')
}
)
puts'inserted'
puts "'#{videos_insert_response.data.snippet.title}' (video id: #{videos_insert_response.data.id}) was successfully uploaded."
rescue Google::APIClient::TransmissionError => e
puts e.result.body
end
return videos_insert_response.data.id #video id
end
def upload_thumbnail video_id, thumbnail_file, thumbnail_size
puts 'uploading thumbnail'
begin
thumbnail_upload_response = ##client.execute({ :api_method => ##youtube.thumbnails.set,
:parameters => { :videoId => video_id,
'uploadType' => 'media',
:onBehalfOfContentOwner => ##youtube_email},
:media => thumbnail_file,
:headers => { 'Content-Length' => thumbnail_size.to_s,
'Content-Type' => 'image/jpg' }
})
rescue Google::APIClient::TransmissionError => e
puts e.result.body
end
end
def get_video_statistics video_id
client = Google::APIClient.new(:key => ##api_key,
:application_name => $PROGRAM_NAME,
:application_version => '1.0.0',
:authorization => nil)
youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)
stats_response = client.execute!( :api_method => youtube.videos.list,
:parameters => {:part => 'statistics', :id => video_id }
)
return stats_response
end
end

Routes. Rails 3

I update apllication from rails 2 to rails 3.
And I rewrite routes with resources. How to write route to this actions:
def delete_attachment
#object = Article.find(params[:id])
attachment = Attachment.find(params['attachment_id'])
attachment.attachment = nil
attachment.destroy
redirect_to :action => 'edit', :id => #object.id
end
def edit_attachment
#object = Article.find(params[:id])
attachment = Attachment.find(params['attachment_id'])
attachment.title = params['attachment_title']
attachment.description = params['attachment_description']
attachment.save
redirect_to :action => 'edit', :id => #object.id
end
def add_attachment
#object = Article.find(params[:id])
attachment = Attachment.new
attachment.attachment = params['attachment_file']
attachment.title = params['attachment_title']
attachment.description = params['attachment_description']
attachment.article_id = #object.id
attachment.save
params['attachment_title'] = nil
params['attachment_description'] = nil
redirect_to :action => 'edit', :id => #object.id
end
This is right solution?
resources :articles do
delete '/articles/delete_attachment', :to => 'articles#delete_attachment'
put '/articles/edit_attachment', :to => 'articles#edit_attachment'
post '/articles/add_attachment', :to => 'articles#add_attachment'
end
I have no way to check it on the server, because there are still many incompatibilities.
You can change the routes to:
resources :articles do
member do
delete 'delete_attachment'
put 'edit_attachment'
post 'add_attachment'
end
end
If you don't have multiple member routes, you can also pass :on to a route, eliminating the block:
Like,
resources :photos do
get 'preview', on: :member
end

I'm trying to make a tweet with grackle, but I get an error:

require 'rubygems'
require 'grackle'
require 'json'
require 'highline/import'
$client = Grackle::Client.new(:auth => {
:type => :auth,
:consumer_key => 'TxnvsqOEHdCTlO2CYBIjw',
:consumer_secret => 'consumer secret',
:token => '2203948560-sfGAMQT69FmSWYrfwuBL2Y3ISyfhB3X3OJ1dyQ2',
:token_secret => 'token secret'
})
class Twitter
##input = ""
def getJsonData
#json = $client.users.show? :screen_name => 'LenguajesP' #http://twitter.com/users/show.json?screen_name=LenguajesP
end
def parseIt
puts #json.name
puts #json.location
puts #json.description
end
def getTweet
##input = ask("Introduzca tweet")
puts ##input
end
def tweet
$client.statuses.update! :status=> ##input #POST to https://twitter.com/statuses/update.json
end
end
This is the error:
Grackle::TwitterError: get http://api.twitter.com/1.1/users/show.json?screen_name=LenguajesP => 400: {"errors":[{"message":"Bad Authentication data","code":215}]}
from /var/lib/gems/1.9.1/gems/grackle-0.3.0/lib/grackle/client.rb:296:in `handle_error_response'
from /var/lib/gems/1.9.1/gems/grackle-0.3.0/lib/grackle/client.rb:274:in `process_response'
from /var/lib/gems/1.9.1/gems/grackle-0.3.0/lib/grackle/client.rb:248:in `call_with_format'
from /var/lib/gems/1.9.1/gems/grackle-0.3.0/lib/grackle/client.rb:228:in `append'
from /var/lib/gems/1.9.1/gems/grackle-0.3.0/lib/grackle/client.rb:166:in `method_missing'
from twit.rb:23:in `tweet'
from (irb):43
from /usr/bin/irb:12:in `<main>'

How do I create a email confirmation?

I'm trying to make a simple email notification when a user signs up.
My user sign up works fine, and I followed the "Sending Email" tutorial exactly but can't get it to work. What am I doing wrong?
user_controller.rb
class Admin::UsersController < InheritedResources::Base
before_filter :admin_only
actions :index, :show, :new, :edit, :create, :update, :destroy
respond_to :html
# def new
# #user = User.new(:invitation_token => params[:invitation_token])
# #user.email = #user.invitation.recipient_email
# end
def create
#user = User.new(params[:user])
UserMailer.deliver_registration_confirmation(#user) < -- where I added the mailer
#user.save(false)
respond_to do |format|
format.html{ redirect_to admin_users_path}
end
end
private
def collection
paginate_options ||= {}
paginate_options[:page] ||= (params[:page] || 1)
paginate_options[:per_page] ||= (params[:per_page] || 20)
#search = User.search(params[:search])
#users ||= #search.all.paginate(paginate_options)
end
end
environments/production.rb
# Settings specified here will take precedence over those in config/environment.rb
config.action_mailer.default_url_options = { :host => 'alpine.totaline.com' }
config.action_mailer.raise_delivery_errors = true
# set delivery method to :smtp, :sendmail or :test
config.action_mailer.delivery_method = :smtp
# these options are only needed if you choose smtp delivery
config.action_mailer.smtp_settings = {
:address => 'smtp.gmail.com',
:port => 25,
:domain => 'alpine.totaline.com',
:authentication => :login,
:user_name => 'emailname#gmail.com',
:password => 'thepassword'
}
models/user_mailer.rb
class UserMailer < ActionMailer::Base
def registration_confirmation(user)
recipients user.email
from "webmaster#alpinechallenge.com"
subject "Thank you for Registering"
body "You are now registered on the Alpine Challenge!"
end
end
Looks like for Gmail you need to use port 587:
# these options are only needed if you choose smtp delivery
config.action_mailer.smtp_settings = {
:address => 'smtp.gmail.com',
:port => '587',
:domain => 'alpine.totaline.com',
:authentication => :login,
:user_name => 'emailname#gmail.com',
:password => 'thepassword'
}
This page contains notes about configuring mail clients for usage with Gmail.

JIRA + Savon + Ruby issues

I am trying to get my new application integrated with JIRA for management of our customer's support tickets. What I had envisioned the system doing was in a before_filter gathering a user's account from within JIRA - from that I can pull up a list of accounts and what not, and if they don't have one then we create one based on their details in the Rails application. Thing is I'm having major issues doing things like removing the user from the jira-users group and adding them to a separate group I have for customers called customer-support. This is the code I have currently:
def current_jira_user
# Fetch the current user in JIRA, if we don't exist, create it!
user_try = #jira.request :get_user do |soap|
soap.body = { :token => #token, :username => "#{current_user.username}" }
end
if user_try.to_hash[:get_user_response][:get_user_return][:href].nil?
# We need to create the user
#jira.request :create_user do |soap|
soap.body = {
:token => #token,
:username => "#{current_user.username}",
:password => UUID.new.to_s,
:fullName => current_user.full_name,
:email => "noreply#XXXXX.XXX" #this is such a hack to get around JIRA's "you've got an account" email
}
end
new_user = RemoteUser.find(current_user.username)
#jira.request :remove_user_from_group do |soap|
soap.body = { :token => #token, :group => RemoteGroup.find('jira-users'), :ruser => new_user }
end
#jira.request :add_user_to_group do |soap|
soap.body = { :token => #token, :group => RemoteGroup.find('customer-support'), :ruser => new_user }
end
new_user[:email] = current_user.email
#jira.request :update_user do |soap| # change their email to the valid one
soap.body = { :token => #token, :ruser => new_user }
end
new_user
else
user_try.to_hash[:get_user_response][:get_user_return]
end
end
def verify_jira_connection
# Verify that we can reach the JIRA instance
#jira = Savon::Client.new do
wsdl.document = JIRA_SOAP_URI
end
#jira.http.read_timeout = 300
#jira.http.auth.ssl.verify_mode = :none
#auth = #jira.request :login do |soap|
soap.body = { :username => JIRA_LOGIN, :password => JIRA_PASSWORD }
end
#token = #auth.to_hash[:login_response][:login_return]
end
## REMOTE CLASSES
class RemoteUser
include Savon::Model
client do
http.headers["Pragma"] = "no-cache"
http.auth.ssl.verify_mode = :none
end
namespace "http://beans.soap.rpc.jira.atlassian.com"
endpoint JIRA_SOAP_URI
basic_auth JIRA_LOGIN, JIRA_PASSWORD
actions :get_user
def self.find(username)
get_user(:username => username).to_hash
end
end
class RemoteGroup
include Savon::Model
client do
http.headers["Pragma"] = "no-cache"
http.auth.ssl.verify_mode = :none
end
namespace "http://beans.soap.rpc.jira.atlassian.com"
endpoint JIRA_SOAP_URI
basic_auth JIRA_LOGIN, JIRA_PASSWORD
actions :get_group
def self.find(group)
get_group(:groupName => group).to_hash
end
end
Users are created just fine, but when I get to the removeUserFromGroup call, I get (soapenv:Server.userException) com.atlassian.jira.rpc.exception.RemoteValidationException: group name cannot be null, needs a value. Using the Jira4R gem is out thanks to our using Ruby 1.9.2. Any help is appreciated. Thanks!
Maybe you need to explicitly send the name?
:group => RemoteGroup.find('jira-users').name
instead of this
:group => RemoteGroup.find('jira-users')
If you were willing to do some rewriting, you could try using a Ruby 1.9-compatible fork of jira4r

Resources