How to get OpenStreetMap access token with devise omniauth-osm - ruby-on-rails

In my controller, I'm trying to get an access token to OSM.
class Auth::OauthController < Devise::OmniauthCallbacksController
def osm
#user = AppUser.from_omniauth(request.env["omniauth.auth"])
token_req = request.env["omniauth.auth"]['extra']['access_token'].consumer.get_request_token(:oauth_verifier => params['oauth_verifier'])
#user.token = token_req.token
#user.token_secret = token_req.secret
sign_in_and_redirect #user
end
end
When I get the access token and writes it to the database.
Next, I try to use the OSM API through oauth gem.
#consumer=OAuth::Consumer.new Settings.osm.consumer_key,
Settings.osm.consumer_secret,
{site: osm_uri}
#access_token = OAuth::AccessToken.new(#consumer, current_user.token, current_user.token_secret)
puts #access_token.get('/api/0.6/user/preferences').body
However, this code does not work in the console I see the authorization error

the error in this code:
token_req = request.env["omniauth.auth"]['extra']['access_token'].consumer.get_request_token(:oauth_verifier => params['oauth_verifier'])
#user.token = token_req.token
#user.token_secret = token_req.secret
correct code
#app_user.token = request.env["omniauth.auth"]['credentials']['token']
#app_user.token_secret = request.env["omniauth.auth"]['credentials']['secret']

Related

Get Input from form for API url Request in rails?

I'm new to Rails and I'm trying to make a simple weather API to get weather by zipcode
is there a way to get the zipcode from user input from a simple form, this will be just for learning so I'm not trying to make users devise, or users model
require 'net/http'
require 'json'
#url = 'http://api.openweathermap.org/data/2.5/weather?zip=#{zipcode}&appid=APIKEY'
#uri = URI(#url)
#response = Net::HTTP.get(#uri)
#output = JSON.parse(#response)
actually I figured it out, i needed to add
def zipcode
#zip_query = params[:zipcode]
if params[:zipcode] == ""
#zip_query = "Hey you forgot to enter a zipcode!"
elsif params[:zipcode]
# Do Api stuff
require 'net/http'
require 'json'
#url = 'http://api.openweathermap.org/data/2.5/weather?zip='+ #zip_query +'&appid=APIKEY'
#uri = URI(#url)
#response = Net::HTTP.get(#uri)
#output = JSON.parse(#response)
#name = #output['name']
# Check for empty return result
if #output.empty?
#final_output = "Error"
elsif !#output
#final_output = "Error"
else
#final_output = ((#output['main']['temp'] - 273.15) * 9/5 +32).round(2)
end
end
end
in the controller.rb file
and add
post "zipcode" => 'home#zipcode'
get "home/zipcode"
in the routes file
but I'm sure this is not the best practice

Facebook Auth log out with Rails and Parse

I am having trouble finding a way to log out from facebook. We are logging in using window.location = '/auth/facebook' which redirects the user to a facebook login page, and calls a callback route /auth/facebook/callback(declared in developers.facebook.com) to a method in my session_controller/create.
The session_controller/create method looks like this
def create
#get auth hash from omniauth
auth = auth_hash
#data = {}
#session_data = {}
#data['id'] = auth['uid']
#data['access_token'] = auth['credentials']['token']
#time must be in iso format, see parse rest api for details under linking
#expiry = Time.at(auth['credentials']['expires_at']).iso8601
#data['expiration_date'] = #expiry
#create new linking user object
user = Parse::User::Facebook.new(#data)
# add other user information to body of PARSE::USER::FACEBOOK instance
user.body['email'] = auth['info']['email']
user.body['auth'] = true
user.body['fullname'] = auth['info']['name']
user.body['ip'] = request.remote_ip
user.body['image'] = auth['info']['image'] if auth['info']['image']
user.body['admin'] = false
user.body['facebookId'] = auth['uid']
user.body['facebookToken'] = auth['credentials']['token']
user.body['has_seen_web_tutorial'] = false
#current_user = user.save
#save necessary session information
session['name'] = #current_user['fullname']
session['points'] = #current_user['points']
session['objectId'] = #current_user['objectId']
session['sessionToken'] = #current_user['sessionToken']
session['image'] = #current_user['image']
session['location'] = #current_user['location']
#session_data['name'] = session['name']
#session_data['fullname'] = #current_user['fullname']
#session_data['points'] = session['points']
#session_data['objectId'] = session['objectId']
#session_data['image'] = session['image']
if auth['info']['image']
File.open('temp_face.png', 'wb') do |file|
file << open(auth['info']['image'], :allow_redirections => :safe).read
end
photo = Parse::File.new({
:body => IO.read("temp_face.png"),
:local_filename => "temp_face.png",
:content_type => "image/png"
})
photo.save
#user.body['image'] = photo
end
image = Parse::Object.new("ImageUploads")
image['fileKey'] = photo
image['owner'] = Parse::Pointer.new({"className" => "_User", "objectId" => session['objectId']})
image['type'] = 'profile'
#image['location']
saved_image = image.save
redirect_to listing_index_path
end
I am having trouble trying to log out. Very new to rails. Any help please?
Thank you

Why Importing gmail contacts using Omnicontacts takes only 99 contacts

I am using omnicontacts to import contacts from gmail. But It takes only 99 contacts not all.
Here is my code
def contacts_callback
#contacts = request.env['omnicontacts.contacts']
#contacts.each do |contact|
contact1 = current_user.contacts.new
contact1.name = contact[:name]
contact1.email = contact[:email]
contact1.group = "Others"
contact1.save(:validate => false)
end
redirect_to "/contact"
end
I can't figure out problem. Please help.
You need to add the max_contacts option in your initializer:
importer :gmail, "xxx", "yyy", :max_results => 1000
I have just updated the README to include this.
Solved it :)
I went to lib/omnicontacts/importer/gmail.rb
def initialize *args
super *args
#auth_host = "accounts.google.com"
#authorize_path = "/o/oauth2/auth"
#auth_token_path = "/o/oauth2/token"
#scope = "https://www.google.com/m8/feeds"
#contacts_host = "www.google.com"
#contacts_path = "/m8/feeds/contacts/default/full"
#max_results = (args[3] && args[3][:max_results]) || 100
end
And I just change #max_results 100 to 500. Now its working

Linkedin Permissions : only serving current position informations

This question is related to the same one here, but still i am facing the same problem that linkedin is only serving the current position informations , how can i get the past positions & education details using the linkedin gem in Rails,my linkedin controller has been shown below, need your assistance.
require 'linkedin'
class LinkedinUserController < ApplicationController
def init_client
key = "XXXXXX"
secret = "XXXXXX"
linkedin_configuration = { :site => 'https://api.linkedin.com',
:authorize_path => '/uas/oauth/authenticate',
:request_token_path =>'/uas/oauth/requestToken?scope=r_basicprofile+r_fullprofile+r_emailaddress+r_network+r_contactinfo',
:access_token_path => '/uas/oauth/accessToken' }
#linkedin_client = LinkedIn::Client.new(key, secret,linkedin_configuration)
end
def auth
init_client
request_token = #linkedin_client.request_token(:oauth_callback => "http://#{request.host_with_port}/linkedin/callback")
session[:rtoken] = request_token.token
session[:rsecret] = request_token.secret
redirect_to #linkedin_client.request_token.authorize_url
end
def callback
init_client
if session[:atoken].nil?
pin = params[:oauth_verifier]
atoken, asecret = #linkedin_client.authorize_from_request(session[:rtoken], session[:rsecret], pin)
session[:atoken] = atoken
session[:asecret] = asecret
else
#linkedin_client.authorize_from_access(session[:atoken], session[:asecret])
end
c = #linkedin_client
c.profile(:fields=>["first_name","last_name","headline","positions","educations"])
end
end
LinkedIn is very particular about access to profile fields and you cannot combine multiple fields which requires 2 different access.
so when you try to get just position details by c.profile(:fields => %w(positions)) it assumes the access of type 'r_basicprofile' whereas educations field require access of type 'r_fullprofile'.so try 2 seperate API calls to retrieve both fields.
"first_name","last_name","headline","positions" available for 'r_basicprofile' member permission,so they can be combined together.

Omniauth for provider authentication in Rails API

I've got omniauth working flawlessly for my rails app on the web. I've also created an API for our iPhone app to interact and I'm trying to get omniauth to work.
Is there a way to pass an access token (received from the integrated iOS integration with the Facebook.app) to omniauth to create the provider entry in the database?
Right now in my web app I have an authentications controller with the following code
def create
omniauth = request.env["omniauth.auth"]
user = User.where("authentications.provider" => omniauth['provider'], "authentications.uid" => omniauth['uid']).first
if user
session[:user_id] = user.id
flash[:notice] = t(:signed_in)
redirect_to root_path
elsif current_user
user = User.find(current_user.id)
user.apply_omniauth(omniauth)
user.save
flash[:notice] = t(:success)
redirect_to root_path
else
session[:omniauth] = omniauth.except('extra')
flash[:notice] = "user not found, please signup, or login. Authorization will be applied to new account"
redirect_to register_path
end
end
In my user controller for the API I created the following:
def create
#user = User.new(params[:user])
#user.save
# Generate data for omni auth if they're a facebook user
if params[:fb_access_token]
graph = Koala::Facebook::API.new(params[:fb_access_token])
profile = graph.get_object('me')
#user['fb_id'] = profile['id']
#user['fb_token'] = params[:fb_access_token]
#user['gender'] = profile['gender']
# Generate omnihash
omnihash = Hash.new
omnihash['provider'] = 'facebook'
omnihash['uid'] = profile['id']
omnihash['info'] = Hash.new
omnihash['info']['nickname'] = profile['username']
omnihash['info']['name'] = profile['name']
omnihash['info']['email'] = profile['email']
omnihash['info']['first_name'] = profile['first_name']
omnihash['info']['last_name'] = profile['last_name']
omnihash['info']['verified'] = profile['verified']
omnihash['info']['urls'] = Hash.new
omnihash['info']['urls']['Facebook'] = profile['link']
omnihash['credentials'] = Hash.new
omnihash['credentials']['token'] = params[:fb_access_token]
omnihash['extra'] = Hash.new
omnihash['extra']['raw_info'] = Hash.new
puts omnihash
# Save the new data
#user.apply_omniauth(omnihash)
#user.save
end

Resources